I have a shell script with the following code:
dir=sample
`mkdir $dir`
`cp /home/bhavya/workspace/UnetStack/logs/log-0.txt $dir/log.txt`
`cd $dir`
In the last line with the cd command in the back quotes, I was not able to cd into the corresponding directory.
But once I removed the back quotes I was able to cd.
What I was wondering is why didn’t the cd work with the back quote?
When you ran:
the shell first ran the command
mkdir $dirin a subshell, capturing its (standard) output, and then ran the captured string as a command. Fortunately, the output was empty, so the second step executed nothing.When you then ran:
the copy was executed in a subshell, and the output was captured and executed. Again, the output was empty, so the second phase of execution did nothing.
Then you ran:
Once more, the
cdoperation was run in a subshell, which exited after changing its own current working directory, but without affecting the parent shell (this is Unix, not a DOS.batcommand file). As before, the output of thecdcommand was captured, and executed, but the output was empty so there was nothing to execute.Essentially, you don’t use back-quotes as extensively as you are doing.
It would be sufficient to write:
Note that if this is in a script, then the normal ways of executing a script would still leave the parent shell in the original directory. There are ways to make it affect the original shell — find out about the
.command (or, inbash, thesourcecommand; that’s easier to search for).You normally use back quotes (or, better, the
$(...)notation) to capture data. For example:The innermost command is
which gcc; it might yield/usr/gcc/v4.7.1/bin/gcc; the innerdirnamethen yields/usr/gcc/v4.7.1/bin; the outer dirname yields/usr/gcc/v4.7.1; the appended/libgivesThat also shows why
$(...)is superior to the back-quote notation:That’s harder to get right, and harder to type!