user437777
user437777

Reputation: 1523

What is the meaning of || after test condition in Bash Script

New to Bash scripting. I came across this line in the script file which I find difficult to understand

[ "$variable" ] || echo 'variable is unset or empty!' >&2

What is || used for?

Upvotes: 0

Views: 329

Answers (4)

David C. Rankin
David C. Rankin

Reputation: 84521

The form of the expression something || something else or something && something else is called a compound command. There can be 2 or more commands and you can use { ...; ...; } to collect multiple commands together after each || or &&. For example, to check that the user provides 2 valid filenames on the command line for a script:

[ -f "$1" ] && [ -f "$2" ] || {
    printf "error: invalid input. Usage: %s <file1> <file2>\n" "${0//\//}"
    exit 1
}

Which simply requires that the test of the first argument [ -f "$1" ] (&& and) the test of the second argument [ -f "$2" ] are both files making each test evaluate to true. Otherwise (|| or) print the error message and exit.

Upvotes: 2

Quill
Quill

Reputation: 2779

Basically, If the first command succeeds the second will never be executed.

1 == 1 || echo 'math is broke'

Upvotes: 3

curtisdf
curtisdf

Reputation: 4210

Roughly translated to English, it means "If it failed, do this instead."

Upvotes: 3

mbsingh
mbsingh

Reputation: 489

It is the logical OR operator. echo is executed if, and only if, test condition returns a non-zero exit status.

See here for more details: http://bash.cyberciti.biz/guide/Logical_OR

Upvotes: 3

Related Questions