0
0
Bash Scriptingscripting~5 mins

test command and [ ] syntax in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the test command do in bash scripting?
The test command checks conditions like file existence or string comparison and returns true or false based on the result.
Click to reveal answer
beginner
How is the [ ] syntax related to the test command?
The [ ] syntax is a shorthand for the test command. For example, [ -f file ] is the same as test -f file.
Click to reveal answer
beginner
What is the correct way to check if a file exists using [ ]?
Use [ -e filename ]. It returns true if the file exists, false otherwise.
Click to reveal answer
intermediate
Why must there be spaces around the brackets in [ ]?
Because [ and ] are separate commands and arguments. Without spaces, bash treats it as one word and errors occur.
Click to reveal answer
beginner
How do you check if two strings are equal using test or [ ]?
Use [ "$str1" = "$str2" ] or test "$str1" = "$str2". Quotes prevent errors if strings are empty or contain spaces.
Click to reveal answer
What does [ -d /home/user ] check?
AIf /home/user is a file
BIf /home/user is empty
CIf /home/user is a directory
DIf /home/user is writable
Which is the correct way to check if variable var is empty?
ABoth A and D
B[ -n "$var" ]
C[ -z "$var" ]
D[ "$var" = "" ]
What happens if you write [ -f file] without space before ]?
AIt works fine
BSyntax error occurs
CIt checks if file is executable
DIt checks if file is a directory
Which command is equivalent to [ "$a" = "$b" ]?
Atest "$a" = "$b"
Btest $a == $b
Ctest $a = $b
Dtest "$a" != "$b"
What does test -e filename check?
AIf filename is empty
BIf filename is executable
CIf filename is a directory
DIf filename exists
Explain how to use the test command and [ ] syntax to check if a file exists and is a directory.
Think about the options for file tests and how [ ] is a shortcut for test.
You got /7 concepts.
    Describe common mistakes when using [ ] in bash scripts and how to avoid them.
    Focus on spacing and quoting to prevent errors.
    You got /5 concepts.