Issue
I have a binary (emulator from the Android SDK Tools) that I use frequently. I've added it to my $PATH variable so that I can easily run the command with solely emulator.
However, it turns out that the binary uses relative paths; it complains if I run the script from a different directory. I'd really like to run the command from any folder without having to cd into the directory where the binary lives. Is there any way to get the script/bash into thinking I ran the command from the directory that it's located in?
Solution
A function is an appropriate tool for the job:
emu() ( cd /dir/with/emulator && exec ./emulator "$@" )
Let's break this down into pieces:
- Using a function rather than an alias allows arguments to be substituted at an arbitrary location, rather than only at the end of the string an alias defines. That's critical, in this case, because we want the arguments to be evaluated inside a subshell, as described below:
- Using parentheses, instead of curly brackets, causes this function's body to run in a subshell; that ensures that the
cdonly takes effect for that subshell, and doesn't impact the parent. - Using
&&to connect thecdand the following command ensures that we abort correctly if thecdfails. - Using
exectells the subshell to replace itself in memory with the emulator, rather than having an extra shell sitting around that does nothing but wait for the emulator to exit. "$@"expands to the list of arguments passed to the function.
Answered By - Charles Duffy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.