Reputation: 11
i am a beginner with bash and im trying to understand someone elses bash script. The script consists of several subsequent invokings of rscripts with certain parameters. All these if statements have roughly the same syntax, as follows:
if Rscript -options > log_file.txt 2>&1
script works, do smth.
else
script failed, leave the ship!
I simply cant get my head around why this if statement does what is does. I know that 2>&1 "combines" stderr and stdout. How does this syntax work exactly?
Thanks for the answers.
Upvotes: 1
Views: 893
Reputation: 409356
The Bash built-in command if
doesn't use the output of the program to determine the condition, it uses the return code or exit status of the "command" used as the condition.
Using e.g.
if anycommand; then
...
fi
is equivalent to
anycommand
if [ $? == 0 ]; then
...
fi
The anycommand
may contain any kind of options and redirections. If you have a series of piped command, the exit code used is the one of the last foreground command, so in a | b | c
the exit code of c
is used.
Also note that an exit code of zero is considered to be a success, i.e. it is true when used in a condition. Any exit code that is non-zero is false.
In a C program the exit code is what the main
function returns, or the value passed to the exit()
function.
In a Bash script or function the exit code is what is passed to the built-in exit
or return
commands.
Upvotes: 3
Reputation: 179
In the above case you mentioned. we are trying to execute a script in a if condition.
if Rscript -options > log_file.txt 2>&1
As per above statement, Rscript is a script and variable "options" stores the argument to run the script. When control executes if condition, first it executes Rscript file with the argument that is stored in options. During the execution of Rscript, all print statements related to Rscript will redirected to "log_file.txt" because of "> log_file.txt". Apart from print statements, error that produced during the execution of the script will also be redirected to text file, because of 2>&1 statement.
2>&1, by this statement we are instructing controller to log all the stderr to stdout, where "log_file.txt" is considered as stdout in this case.
Finally, if Rscript returns true value then control will enter into if condition , If not control will execute else condition.
Upvotes: 0
Reputation: 1759
The numbers are the file descriptor numbers : 2 is the standard error output (stderr) and 1 is the standard output (stdout), so by writing 2>&1 you are saying : redirect the output from 2 (stderr) to the same as 1 (stdout), and in your command it means to log_file.txt.
Upvotes: 0