Call a command as if it were in called in another directory

I'm using a command line program whose documentation states:

"You can run XXX on input located in another directory, but its output will always be put in the current working directory". I'd like to have the output written to another directory though.

I could (either with cd, or pushd + popd)

  1. change to the output directory
  2. run the command so the output is put there
  3. then change back

or

  1. run the command in my current location
  2. move the output to the output folder

...but both seem clunky, and prone to errors if the script were to be edited by someone who isn't aware of this requirement. The only other solution I can think of is to join the commands with semicolons. Is there another way?

This is in bash by the way.


Solution 1:

use parentheses, so the cd occurs in a subshell:

(cd other_dir && xxx)

When that ends, your current working dir will not have changed.

cd can fail, so use && to conditionally execute the program.