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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With