z.k
z.k

Reputation: 45

why if expression is always true in bash script

I'm very new in shell script and I wrote this code to copy an input file from directory new1 to directory new2 if the file doesn't exist in second directory.

the problem is that the first if expression is always true and the code always print "file copied successfully" even if the file exists in second directory.

here is my code:

while true; do
            echo "enter a file name from directory new1 to copy it to directory new2 "
            echo "or enter ctrl+c to exit: "
            read input
            i=0
            cd ~/new2 
            if [ -f ~/new1/$input ]; then
                    i=1                    
            fi
            if [ $i -eq 0 ];then                   
                    cp ~/new1/$input ~/new2/
                    echo "####" $input "copied successfully ####"
            else
                    echo "#### this file exist ####"
            fi
done

I will be appreciated if any one tell me how to fix this problem

Upvotes: 3

Views: 323

Answers (1)

tripleee
tripleee

Reputation: 189317

You are comparing the wrong file. In addition, you probably want to refactor your logic. There is no need to keep a separate variable to remember what you just did.

while true; do
    echo "enter a file name from directory new1 to copy it to directory new2 "
    echo "or enter ctrl+c to exit: "
    read input
    #i=0         # no use
    #cd ~/new2   # definitely no use
    if [ -f ~/new2/"$input" ]; then  # fix s/new1/new2/
        # diagnostics to stderr; prefix messages with script's name
        echo "$0: file ~/new2/$input already exists" >&2
    else
        cp ~/new1/"$input" ~/new2/
        echo "$0: ~/new1/$input copied to ~/new2 successfully" >&2
    fi
done

Take care to make your diagnostic messages specific enough to be useful. Too many beginner scripts tell you "file not found" 23 times but you don't know which of the 50 files you tried to access were not found. Similarly, including the name of the script or tool which produces a diagnostic in the diagnostic message helps identify the culprit and facilitate debugging as you start to build scripts which call scripts which call scripts ...

As you learn to use the command line, you will find that scripts which require interactive input are a dog to use because they don't offer command history, tab completion of file names, and other niceties which are trivially available to any tool which accepts a command-line file argument.

cp -u already does what this script attempts to implement, so the script isn't particularly useful per se.

Note also that ~ is a Bash-only feature which does not work with sh. Your script otherwise seems to be compatible with POSIX sh and could actually benefit from some Bash extensions such as [[ if you are going to use Bash features anyway.

Upvotes: 5

Related Questions