0

If I execute the below rsync command in command-line , I am getting the proper return status

/usr/bin/rsync -azv -p /home/zaman x11server:/home/zamanr &> rsyncjob/output."$datetime"

echo $?
255

The hostname is unreachable , so I am getting a return value of 255

This is fine for me. But If I put the same command in a bash script , then I am not getting any return value

#!/bin/bash
datetime=`date +%Y.%m.%d`
ret_value= `/usr/bin/rsync -azv -p /home/zaman x11server:/home/zamanr &> rsyncjob/output."$datetime"`
echo $ret_value

The output of script just shows blank . The $ret_value is not printed.

What I am missing here to get the return value of the rsync command printed via script.

1

try this.

#!/bin/bash
datetime=`date +%Y.%m.%d`
ret_value=`/usr/bin/rsync -azv -p /home/zaman x11server:/home/zamanr &> rsyncjob/output."$datetime"; echo $?`
echo $ret_value

The issue is that the command you are running doesn't produce an output since you are piping it to a file. Appending the command to echo the last command exit code should give you the result you are seeking.

1

The line

ret_value= `…`

has a weird behavior. It first executes the command inside the backticks. The output of that command is then split into words, and the first word is used as a command to execute. If there was at least one word, it would be executed as a command (with the other words as parameters), with the environment variable ret_value set to the empty string for the duration of that command only. But since the output of the command in backticks happens to be empty, what happens instead is that the line is an assignment: it sets the shell variable ret_value to the empty string.

You probably meant to write

ret_value=`…`

with no space after the equal sign. That would set ret_value to the output of the command in backticks — that's what backticks mean. Remember that in the shell, spaces are significant, and in particular you can't have spaces inside an assignment.

If you want to get the return value of a command, run that command (with its output going wherever you like), and then read the content of the special variable $?. The $? variable contains the status of the previous command that was executed.

/usr/bin/rsync -azv -p /home/zaman x11server:/home/zamanr &> rsyncjob/output."$datetime"
echo $?

You may want or even need to save $? into another variable, since it will change as soon as one more command has been executed.

/usr/bin/rsync -azv -p /home/zaman x11server:/home/zamanr &> rsyncjob/output."$datetime"
ret_value=$?
if [ $ret_value -eq 0 ]; then
  echo "Success"
else
  echo "Failure, rsync return status $ret_value"
fi
exit $ret_value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.