0
0
Bash Scriptingscripting~5 mins

File existence checks in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What command checks if a file exists in a bash script?
Use the test command with -e flag: if [ -e filename ]; then checks if the file named 'filename' exists.
Click to reveal answer
beginner
What does the -f flag check in a bash file test?
The -f flag checks if the file exists and is a regular file (not a directory or special file).
Click to reveal answer
beginner
How do you check if a directory exists in bash?
Use -d flag: if [ -d directoryname ]; then checks if 'directoryname' exists and is a directory.
Click to reveal answer
intermediate
What is the difference between -e and -f in bash file tests?
-e checks if a file or directory exists. -f checks if a regular file exists (not directory).
Click to reveal answer
beginner
Write a simple bash script snippet that prints 'File found' if a file named 'data.txt' exists.
if [ -e data.txt ]; then
  echo "File found"
else
  echo "File not found"
fi
Click to reveal answer
Which bash test flag checks if a file exists regardless of type?
A-f
B-e
C-d
D-x
What does the -d flag check in bash?
AIf a file is executable
BIf a regular file exists
CIf a directory exists
DIf a file is empty
What will this script print if 'myfile' does not exist?
if [ -f myfile ]; then echo "Found"; else echo "Not found"; fi
AFound
BNothing
CError
DNot found
Which test flag would you use to check if a file is executable?
A-x
B-r
C-w
D-e
What does this script check?
if [ -e /tmp ]; then echo "Exists"; fi
AIf /tmp exists (file or directory)
BIf /tmp is a directory
CIf /tmp is a regular file
DIf /tmp is executable
Explain how to check if a file exists in a bash script and what flags you can use for different file types.
Think about the test command and its flags.
You got /4 concepts.
    Write a bash script snippet that checks if a directory named 'backup' exists and prints a message accordingly.
    Use the -d flag inside an if condition.
    You got /4 concepts.