How to run a file in a different directory

There is a file that I would like execute in a different folder, under about four sub-directories.

For example:

My pwd may be /home/directoryA. However, the file I would like execute may be in directoryD. At the moment if I want to execute the file I would need to go to cd /home/directoryA/directoryB/directoryC/directoryD/ and then execute the file. Or I might have do something like src /directoryA/directoryB/directoryC/directoryD/somefile

  1. Is it possible to execute the file without actually being in the directory where the file is?

  2. Is there a shortcut way of executing the file somefile without going into the directory?


Solution 1:

No you don't need to use:

cd home/directoryA/directoryB/directoryC/DirectoryD
./somefile 

You can simply run the command by prefixing it with its path:

/home/directoryA/directoryB/directoryC/DirectoryD/somefile

Because you are already in the /home/directoryA you can use the current directory shortcut . and run the command like this:

./directoryB/directoryC/DirectoryD/somefile

I noticed OP has expanded scope via comments under other answers. Here is some additional information:

  • To find out where somefile is located use: locate somefile.
  • If somefile was added today you need to first update the locate database by running sudo updatedb.
  • When there are multiple versions of somefile located in the PATH you can find out which one is executed first use which somefile.
  • If you want to run somefile without specifying a directory name in front put it in the path. To check the path use echo $PATH. Common path locations to put somefile are /usr/local/bin (if it uses sudo powers) and /home/your_user_name/bin (you might have to create the directory first).
  • You can also add /home/directoryA/directoryB/directoryC/DirectoryD/ to your path but that would be highly unusual. However you could then simply type somefile no matter what directory you are in and it will run.
  • Of course somefile must be executable which you set with the command: chmod a+x /home/directoryA/directoryB/directoryC/DirectoryD/somefile

Solution 2:

Sure! If somefile is marked as executable, you can run it with

~/directoryA/directoryB/directoryC/DirectoryD/somefile

Want to know if somefile is executable? Go to its directory and run

find . -maxdepth 1 -perm -111 -type f

to see all the executables in that directory.