3

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?

3
  • Note: I know I can call it manually with (cd /X/Y/Z; ./script.sh), but I need the script to be run routinely in a crontab Commented Mar 3, 2017 at 21:25
  • crontab actually takes a string to run with /bin/sh -c "yourstring" (replacing /bin/sh if your crontab provides its own SHELL variable), so it is not in fact limited to one command at a time. Commented Mar 3, 2017 at 21:26
  • and btw, if you're going to be doing it in parens like that, use 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 an exec, rather than running your script.sh as a subprocess of the subshell that is itself a subprocess. Commented Mar 3, 2017 at 21:29

1 Answer 1

3

Put a cd statement in the script, just like you'd type to set your working directory from an interactive bash shell.

Sign up to request clarification or add additional context in comments.

1 Comment

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