Skip to content
Advertisement

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.

Thanks

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

Advertisement

Answer

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"
Advertisement