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

I am new to bash scripting and learning some examples. One example I've seen is to use if-statement to check if the previously assigned output file is valid, for example:

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

I understand what [ -n "$outputFile" ] does, but not all the others are conditional. Can anyone explain what that means ! 2>/dev/null : >> $outputFile ! 2>/dev/null : >> $outputFile / does?

I have answers for answers, but most of the links found were I / O redirect explanations that are definitely relevant but still unclear about the structure ! : >> ! : >> .

+7
linux bash
source share
2 answers

Something is strange written!

Command : built in to bash. This is equivalent to true ; he does nothing, successfully.

 : >> $outputFile 

tries to do nothing and adds (empty) output to $outputFile - which is already validated as a non-empty string. The redirection operator >> will create the file if it does not already exist.

I / O redirection, such as 2>/dev/null , can occur anywhere in a simple command; they should not be at the end. Thus, the stdout command of the : (which is empty) command is added to $outputFile , and any stderr output is redirected to / dev / null. Any such stderr output would be the result of a denial of redirection, because the command : itself does nothing and will not stop doing it. I don't know why the stdout redirection (to the end of $outputFile and the stderr redirection (to /dev/null ) are on opposite sides of the command :

The operator ! is a logical "not"; it checks the execution of the next command and inverts the result.

Final result written in English:

if "$ outputFile" is set and is not an empty string, and if we do not have permission to write to it, then end the script with status 1.

In short, it checks to see if we can write to $outputFile , and is reset if we don't.

+5
source share

The script tries to make sure that $outputFile is writable in a less obvious way.

: - This is a null command in bash , it does nothing. The fact that stderr redirected to /dev/null is just suppressing the rejected resolved error if that happens.

If the file is not writable, the command does not work, which makes the condition true because it was canceled with ! and script.

+4
source share

All Articles