thisissami
thisissami

Reputation: 16383

How can I trick bash to think I ran a script from within the directory where the binary is located?

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?

Upvotes: 1

Views: 82

Answers (3)

Charles Duffy
Charles Duffy

Reputation: 295815

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 cd only takes effect for that subshell, and doesn't impact the parent.
  • Using && to connect the cd and the following command ensures that we abort correctly if the cd fails.
  • Using exec tells 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.

Upvotes: 2

Cyrus
Cyrus

Reputation: 88949

Add an alias (emu) to your ~/.bashrc:

alias emu="(cd /dir/with/emulator; ./emulator)"

Upvotes: 1

bennerv
bennerv

Reputation: 86

I would look into command line aliases.

If you are in linux and using bash you can go to ~/.bash_profile and add a line such as:

alias emulator='./path-to-binary/emulator"

On windows it's a little different. Here is an example on how to do a similar thing in windows.

Upvotes: 0

Related Questions