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.
$ 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.
“$?” 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.
$?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With