The back-ticks around each command in your script will cause the shell to take the output of the command and execute that as a command.
Using back-ticks around a command is equivalent of putting the command inside $( ... )
(this is the preferred syntax for capturing the output of a command).
The error message /home/user/final: Is a directory
comes from ksh
trying to execute the result of pwd
as a command, and likewise, total: command not found
from trying to execute the result of ls -l
.
Remove the back-ticks. Also remove the semi-colons (;
). These are only needed if you want to put two commands on the same line:
cd dir; pwd
Your script should look something like
#!/bin/sh
cd "their_file"
pwd
ls -l
Note that this will still execute pwd
and ls -l
if the cd
fails. To exit the script if cd
fails:
#!/bin/sh
cd "their_file" || exit 1
pwd
ls -l
This uses the fact that cd
returns a non-zero exit status if it fails. The ||
(logical or) in front of exit 1
means that the script will go on to execute the exit
statement if cd
returns "false" (which in shell scripts is what a non-zero exit status means).
The reason you get /home/user/final: Is a directory
and not /home/user/final/their_file: Is a directory
is because the cd
is executed in a sub-shell (which is what happens when you put it in back-ticks or within $( ... )
). Since it's executed in a sub-shell, the actual changing of the working directory is not reflected in the parent shell (your script).
For the same reason, you will notice that when your script has finished executing, you will still be in the same directory as when you invoked the script, and not in the their_file
directory.
For more on this particular thing, see "why cd function in script doesn't work" and "Script to change current directory (cd, pwd)" (and other similar questions).