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?
✗ Incorrect
The -e flag checks if a file or directory exists, regardless of type.
What does the
-d flag check in bash?✗ Incorrect
The -d flag checks if the given path exists and is a directory.
What will this script print if 'myfile' does not exist?
if [ -f myfile ]; then echo "Found"; else echo "Not found"; fi
✗ Incorrect
Since 'myfile' does not exist, the condition fails and 'Not found' is printed.
Which test flag would you use to check if a file is executable?
✗ Incorrect
The -x flag checks if the file is executable.
What does this script check?
if [ -e /tmp ]; then echo "Exists"; fi
✗ Incorrect
The -e flag checks if the path exists, whether file or directory.
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.