I have a script in /A/B/script.sh. When called, it needs to operate on files in /X/Y/Z. How can I set a working directory specifically for the script, in the script?
1 Answer
Put a cd statement in the script, just like you'd type to set your working directory from an interactive bash shell.
1 Comment
Charles Duffy
Actually -- in the script, it should have error handling. ie.
cd /X/Y/Z || exit -- a human running things interactively will notice when a cd fails, a script will otherwise modify files in the wrong directory. See github.com/koalaman/shellcheck/wiki/SC2164
/bin/sh -c "yourstring"(replacing/bin/shif your crontab provides its ownSHELLvariable), so it is not in fact limited to one command at a time.exec:(cd /X/Y/Z && exec ./script.sh)-- that way the cost you pay to spawn the subshell that the parens ask for is evened out by consuming that subshell via anexec, rather than running yourscript.shas a subprocess of the subshell that is itself a subprocess.