Run program from anywhere without changing directory

DON'T CD, just run it using its absolute path

This version:

cd /home/path_to_x && ./x

changes directory to an absolute path (you see how /home/... starts at the root directory) and then runs the executable at the relative path ./x (that is, relative to the new working directory).

This version:

./home/path_to_x/x

tries to run the executable at the relative path ./home/path_to_x/x, which means relative to whatever your current working directory is now. That explains why you get the error - this relative path really doesn't exist.

The command you want would be:

/home/path_to_x/x

using the absolute path (starting at the root directory /) again.

Oh, and you can also just add /home/path_to_x to your PATH instead of creating the alias. See: How to run scripts without typing the full path?


If you do not want the cd to stick after the alias substitution, use a subshell with ( y ):

alias my_x="(cd /home/path_to_x && ./x)&" 

you can check it with

alias test_y="(cd /tmp && sleep 10 ) & "

Note that the solution

alias my_y="/home/path_to_x/x" 

is not exactly equivalent. In fact, if called via my_x, the x program is run with a current directory /home/path_to_x/, while if called by my_y, x is run with a current directory which is the one where the command my_y was issued. This can be important or not depending on what x is doing.

About the OP solution, it works in bash:

romano@RRyS:~$ pwd
/home/romano
romano@RRyS:~$ alias x="cd /bin && ./echo A >/dev/null  &"
romano@RRyS:~$ x
[1] 16611
romano@RRyS:~$ pwd
/home/romano

but not in zsh:

[romano:~] % pwd
/home/romano
[romano:~] % alias x="cd /bin && ./echo A >/dev/null &"
[romano:~] % x
[1] 16744
[1]  + 16744 done       ./echo A > /dev/null                                    
1& [romano:/bin] % pwd
/bin
[romano:/bin] % 

It seems that bash and zsh execute lists in different ways ...so it's better to add the explicit parenthesis... thanks @EliahKagan for pointing it to me.


If the file which you want to run is already executeable, why don't you add it to you PATH variable?

If your executable file is /home/user/aplication/appX just enter

PATH=$PATH:/home/user/application

to your ~/.bashrc or ~/.profile

After restarting your console, you can run it simply with appX

I think this is the most clean solution.