Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verifying that a copy succeeded

I would like to write a script that verifies if a copy succeeded or not. Here's what I have:

#!/bin/sh
cp home/testing/present.txt home/testing/future.txt
   echo "Copy Code: $? - Successful"
if [ $? != 0 ]; then
   echo "Copy Code: $? - Unsuccessful"
fi

The "if" statement is not being initialized. How can resolve this? Thank You for your time.

like image 597
Eddie_One Avatar asked Mar 13 '15 17:03

Eddie_One


People also ask

How can I determine whether a command executed successfully?

$ echo $? If a command succeeded successfully, the return value will be 0. If the return value is otherwise, then it didn't run as it's supposed to. Let's test it out.

Which command is used to verify the last command successfully executed?

“$?” is a variable that holds the return value of the last executed command. “echo $?” displays 0 if the last command has been successfully executed and displays a non-zero value if some error has occurred.


1 Answers

$? refers to the last command:

#!/bin/sh
cp home/testing/present.txt home/testing/future.txt
   echo "Copy Code: $? - Successful"   # last command: cp
if [ $? != 0 ]; then                   # last command: echo
   echo "Copy Code: $? - Unsuccessful" # last command: [
fi

If you want to repeatedly work with the status of a specific command, just save the result in another variable:

#!/bin/sh
cp home/testing/present.txt home/testing/future.txt
status=$?
echo "Copy Code: $status - Successful"
if [ $status != 0 ]; then
   echo "Copy Code: $status - Unsuccessful"
fi

However, a better approach is to simply test the cp command in the first place:

if cp home/testing/present.txt home/testing/future.txt
then
  echo "Success"
else
  echo "Failure, exit status $?"
fi
like image 192
that other guy Avatar answered Oct 28 '22 02:10

that other guy