Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this if-statement from a bash script do?

Tags:

linux

bash

I am new to bash scripting and learning through some examples. One of the examples that I saw is using an if-statement to test if a previously assigned output file is valid, like this:

if [ -n "$outputFile" ] && ! 2>/dev/null : >> $outputFile ; then
    exit 1
fi

I understand what [ -n "$outputFile" ] does but not the rest of the conditional. Can someone explain what ! 2>/dev/null : >> $outputFile mean/does?

I have googled for answers but most links found were explanations on I/O redirection, which are definitely relevant but still unclear about the ! : >> structure.

like image 453
BigHead Avatar asked Aug 27 '14 20:08

BigHead


2 Answers

That's some oddly written code!

The : command is built into bash. It's equivalent to true; it does nothing, successfully.

: >> $outputFile

attempts to do nothing, and appends the (empty) output to $outputFile -- which has already been confirmed to be a non-empty string. The >> redirection operator will create the file if it doesn't already exist.

I/O redirections such as 2>/dev/null can appear anywhere in a simple command; they don't have to be at the end. So the stdout of the : command (which is empty) is appended to $outputFile, and any stderr output is redirected to /dev/null. Any such stderr output would be the result of a failure in the redirection, since the : command itself does nothing and won't fail to do so. I don't know why the redirection of stdout (onto the end of $outputFile and the redirection of stderr (to /dev/null) are on opposite sides of the : command.

The ! operator is a logical "not"; it checks whether the following command succeeded, and inverts the result.

The net result, written in English-ish text is:

if "$outputFile" is set and is not an empty string, and if we don't have permission to write to it, then terminate the script with a status of 1.

In short, it tests whether we're able to write to $outputFile, and bails out if we don't.

like image 174
Keith Thompson Avatar answered Sep 17 '22 16:09

Keith Thompson


The script is attempting to make sure $outputFile is writable in a not-so-obvious way.

: is the null command in bash, it does nothing. The fact that stderr is redirected to /dev/null is simply to suppress the permission denied error, should one occur.

If the file is not writable, then the command fails, which makes the condition true since it's negated with ! and the script exits.

like image 35
FatalError Avatar answered Sep 17 '22 16:09

FatalError