Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Bash execute a command in a different directory context?

I have a common command that gets called from within very specific directories. There is only one executable sitting in /bin for this program, and the current working directory is very important for running it correctly. The script affects the files that live inside the directory it is run within.

Now, I also have a custom shell script that does some things in one directory, but I need to call that command mentioned above as if it was in another directory.

How do you do this in a shell script?

like image 475
Marty Wallace Avatar asked May 12 '12 18:05

Marty Wallace


People also ask

How do I run a Bash file in another directory?

Assuming /A/B/C/script.sh is the script, if you're in /A , then you'd type ./B/C/script.sh or bash B/C/script.sh or a full path, /A/B/C/script.sh . If what you mean is that you want that script always to work, then you'll want to add it to your PATH variable.

How do I go to a specific directory in Bash?

To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.


2 Answers

Use cd in a subshell; the shorthand way to use this kind of subshell is parentheses.

(cd wherever; mycommand ...) 

That said, if your command has an environment that it requires, it should really ensure that environment itself instead of putting the onus on anything that might want to use it (unless it's an internal command used in very specific circumstances in the context of a well defined larger system, such that any caller already needs to ensure the environment it requires). Usually this would be some kind of shell script wrapper.

like image 135
geekosaur Avatar answered Oct 19 '22 14:10

geekosaur


You can use the cd builtin, or the pushd and popd builtins for this purpose. For example:

# do something with /etc as the working directory cd /etc :  # do something with /tmp as the working directory cd /tmp : 

You use the builtins just like any other command, and can change directory context as many times as you like in a script.

like image 42
Todd A. Jacobs Avatar answered Oct 19 '22 16:10

Todd A. Jacobs