I am new to scripting , I am trying to rebuild a script based on an old script. Can someone help me figure out what the script is doing? This is only a part of the script.
I am looking to interpret these two points in the scripts:-
1)
test=`echo $?`
while [ $test -eq 2 ]
I do not understand when its doing test='echo $?', what is assigned in this step to test
$? is a special variable, the return code of the last command. The return code is a number, zero for success, anything else for error.
$ true
$ echo $?
0
$ false
$ echo $?
1
$
...but they didn't need to use backticks `` (same key as ~) to get it into the variable test. Commands in backticks become strings, so you could do things like LINE=`grep username /etc/passwd` to read a matching line from a file into a variable.
All they had to do though, was test="$?"
Depends what command is, of course. The redirections are sending all its output into the log file, yes.
function demo {
echo '####' >> $LOG_FILE
echo 'Starting the test:' >> $LOG_FILE
command -f $ETC/$LCL_FILE recreate >> $LOG_FILE 2>&1
test=`echo $?`
while [ $test -eq 2 ]
do
echo '. Sleeping ...' >> $LOG_FILE
sleep $LOOP_SLEEP
command -f $ETC/$LCL_FILE recreate >> $LOG_FILE 2>&1
test=`echo $?`
done
if [ $test -eq 0 ]
then
echo >> $LOG_FILE
date >> $LOG_FILE
echo 'The recreate was successfully completed for file $LCL_FILE.' >> $LOG_FILE
What the script is doing, is running command over and over until it succeeds. When it fails, it must be returning 2, since that's what the loop checks for, and when it does, it keeps running it until it returns (in $?) something else.
Strongly advise that you do not name an Environment Variable with the same name as the unix command test .
The value of $? is the integer exit code of the most recent command executed in your Shell. Exit code zero means "non-failure" of the command itself. Other values should be documented for the program but can often be a matter of "test-and-detect".