Skip to content

struggling with a shell script in linux

I am trying to create a script that takes two arguments, source folder and target folder. I am trying to show an error message if the source directory is not found and exit the program. If target directory is not found, I would like it to create that directory. Then I would like to copy all the contents from the source directory to the target directory.

When I run the program with two arguments passed, e.g. /mnt/sdb1 and -root/my-documents/photoarch, I will get the error:

cp: cannot stat ‘/mnt/adb1/’: No such file or directory

I would like it to show my error that I have coded and create the folder if not already created but it does not do this.


#checking that arguments exist
if [ $# -eq 0 ]; then
    echo "Usage: phar image_path archive_path"
elif [ -d $1 ]; then
    echo "Source directory not found"
elif [ -d $2 ]; then
    mkdir ~root/my-documents/$2
    cp -r $1 $2



You are missing negations:

elif [ ! -d $1 ]; then
elif [ ! -d $2 ]; then

As a best-practice recommendation, I suggest you enclose all occurrences of $1 and $2 in double quotes. Otherwise you might run into problems with paths containing spaces. For example:

cp -r "$1" "$2"