简体   繁体   中英

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, eg /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

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"

In the 3rd elif clause, you make the destination directory if it doesn't already exist, but you create it as a subdirectory of root's home directory and then attempt to copy to the non-existent directory that you just verified doesn't exist (once you invert the flags as @Stefan Majewsky noted). If you are going to be creating the destination directory as a subdirectory of root's home (or anywhere else, for that matter), I would recommend restructuring your code somewhat to set variables such as SRCDIR and DSTDIR so that you can more easily manipulate them if they need to change. With this, you could have the code read something like this:

#!/bin/sh
clear
#checking that arguments exist
if [ $# -eq 0 ]; then
    echo "Usage: phar image_path archive_path"
    exit 1
fi
SRCDIR="$1"
DSTDIR="$2"

if [  ! -d $SRCDIR ]; then
    echo "Source directory not found"
    exit
elif [ ! -d $DSTDIR ]; then
    DSTDIR="~root/my-documents/$DSTDIR"
    echo "Creating destination directory $DSTDIR"
    mkdir $DSTDIR
fi

cp -r "$SRCDIR/*" "$DSTDIR"

I hope this answers your question adequately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM