If the command in question is always going to be a git command, you should just use the --git-dir
and --work-tree
options to tell git what to do! (Or if you're doing this a lot over the course of a script, set the variables GIT_DIR and GIT_WORK_TREE to the appropriate paths)
If this is a general question, I believe Andrzej has a start on the best suggestion: use a subshell. The proper way to start a subshell, though, is to use parentheses, not to use command substitution (unless you actually want to capture the output):
( cd $dir && run_command )
The other solution, as suggested by Felix and ibread, will of course work, but do be careful - if the command you're executing is perhaps a shell function, then it could also cd, and change the effect of the cd -
at the end. The safest thing in the general case is to store the current directory in a variable first.