The keywords here is: running command with different working directory. You can google it yourself to find more information.
You can call it using parentheses - ()
$ (cd ../../../../tools/msp430/bin &&./msp430-gcc)
Parentheses will create a new subshell to execute commands inside it. This new subshell will change directory and execute program in this directory.
Quote from man bash
(list) list is executed in a subshell environment (see COMMAND
EXECUTION ENVIRONMENT below). Variable assignments and builtin
commands that affect the shell's environment do not remain in
effect after the command completes. The return status is the
exit status of list.
where a list
is just a normal sequence of commands.
Variables in a subshell are not visible outside the block of code in the subshell.
They are not accessible to the parent process, to the shell that launched the
subshell. These are, in effect, local variables.
Directory changes made in a subshell do not carry over to the parent shell.
In conclusion: subshell will see all variables from parent shell
, but it will use them as local. Changes made by subshell to variables not affect parent shell
Another method using sh
:
$ sh -c 'cd ../../../../tools/msp430/bin; ./msp430-gcc'
In this case sh -c
will not spawn subshell, but create own new shell. That's why it cannot see parent shell
variables. So remember: if you set some variable before executing sh -c
new shell will not see it.
But there is also a little confuse between using single quotes ''
and double quotes ""
in sh -c
. See this question to understand difference, I will only show little example:
$ TEST=test1
$ sh -c 'echo $TEST'
$ sh -c 'TEST=test2;echo $TEST'
test2
after executing first command nothing was printed out. It's because new shell do not have TEST
variable, and ''
do not expand $TEST
.
$ sh -c "echo $TEST"
test1
$ sh -c "TEST=test2;echo $TEST"
test1
here first command $TEST
was expanded because of using ""
, and even if we set TEST
variable in new shell $TEST
already expanded, and it printed out test1
Sources
- About
sh -c "command"
. Very full answer.
- About parentheses
- Similar question
- From bash guide about parentheses
- Difference between
''
and ""