← Linux and the Command Line Lesson 44 of 51 · 10 XP

Comparison operators: test

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Conditions are checked by the test command, or its short form [ … ]. The spaces inside the brackets are a must: [ "$a" = "$b" ].

Strings:

[ "$a" = "$b" ] equal
[ "$a" != "$b" ] not equal
[ -z "$a" ] empty
[ -n "$a" ] not empty

Numbers — letter operators (< and > would be redirection here!):

-eq / -ne equal / not equal
-lt / -le less than / less than or equal
-gt / -ge greater than / greater than or equal

Files:

-e path exists
-f path is an ordinary file
-d path is a folder
-r / -w / -x can be read / written / executed
-s path the file isn't empty

Combining: [ "$a" -gt 0 ] && [ "$a" -lt 10 ]. Negation: [ ! -f file ].

bash has [[ … ]] — more convenient (&& inside, patterns, =~ for regular expressions), but it isn't POSIX.

Task. The script gets a number as an argument. Print one word: negative, zero or positive, and on the second line — even or odd.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.