According to the question:
Could the variable $?
be overwritten when another command is executed in between?
The answer is YES. The variable $?
contains the exit status of the last task. For example:
$ false; echo $?
1
$ false; true; echo $?
0
$ false; true; false; echo $?
1
Like as the variable $!
contains the PID of the last background task.
Reference: Devhints.io: Bash scripting cheatsheet
According to the question:
Is the wait $oldpid
messing with the asynchronous way of nohup
?
It shouldn't - isn't it designed exactly for such tasks? :)
According to the question:
Or maybe this logic is just dumb and there is simply a better approach?
For me it is not clear why you pushing the rsync
into the background and then wait
for it instead just execute the command and then do the test.
#!/bin/bash
rsync -a source.file destination.file 2>/dev/null
if [[ $? -eq 0 ]]; then echo "SUCCESS"; else echo "FAILED"; fi
2>/dev/null
is used here to suppress the error messages of rsync
, but you can save them in a temp file and attach it to the email.
But probably it is not the entire script...
In addition, in the first rows of help wait
is provided the following information.
wait: wait [-fn] [id ...]
Wait for job completion and return exit status.
So you can use the output of wait
directly within the if
statement. I've already done successful test for this approach.
#!/bin/bash
nohup rsync -a source.file destination.file 2>/dev/null &
oldpid=$!
if wait $oldpid
then
echo "SUCCESS"
else
echo "FAILED"
fi
2>/dev/null
is used here to suppress the error messages of nohup
, while rsync
error messages goes somewhere in the background.