Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

bash - Why doesn't my if statement with backticks work properly?

I am trying to make a Bash script where the user will be able to copy a file, and see if it was successfully done or not. But every time the copy is done, properly or not, the second output "copy was not done" is shown. Any idea how to solve this?

if [ `cp -i $files $destination` ];then
        echo "Copy successful."
else
        echo "Copy was not done"
fi
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you want is

if cp -i "$file" "$destination"; then #...

Don't forget the quotes.


You version:

if [ `cp -i $files $destination` ];then #..

will always execute the else branch.

The if statement in the shell takes a command. If that command succeeds (returns 0, which gets assigned into $?), then the condition succeeds.

If you do if [ ... ]; then, then it's the same as if test ... ; then because [ ] is syntactic sugar for the test command/builtin.

In your case, you're passing the result of the stdout* of the cp operation as an argument to test

The stdout of a cp operation will be empty (cp generally only outputs errors and those go to stderr). A test invocation with an empty argument list is an error. The error results in a nonzero exit status and thus you always get the else branch.


*the $() process substitution or the backtick process substitution slurp the stdout of the command they run


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...