0
0
Bash Scriptingscripting~10 mins

File existence checks in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - File existence checks
Start
Check if file exists
End
The script checks if a file exists, then prints a message based on the result.
Execution Sample
Bash Scripting
filename="test.txt"
if [ -e "$filename" ]; then
  echo "File exists"
else
  echo "File does not exist"
fi
This script checks if 'test.txt' exists and prints a message accordingly.
Execution Table
StepActionConditionResultOutput
1Set filename to 'test.txt'N/Afilename='test.txt'
2Check if file exists with [ -e "$filename" ][ -e "test.txt" ]True if file exists, False if not
3If condition TrueFile exists?Yesecho 'File exists'
4Print outputN/AN/AFile exists
5If condition FalseFile exists?Noecho 'File does not exist'
6Print outputN/AN/AFile does not exist
💡 Script ends after printing the appropriate message based on file existence.
Variable Tracker
VariableStartAfter Step 1Final
filenameundefinedtest.txttest.txt
Key Moments - 3 Insights
Why do we use quotes around "$filename" in the condition?
Quoting "$filename" prevents errors if the filename contains spaces or is empty, ensuring the condition checks the correct string as shown in step 2 of the execution_table.
What does the -e option check in the condition?
The -e option checks if the file exists regardless of type (file, directory, etc.), as seen in step 2 where the condition evaluates file existence.
Why is there an else branch in the script?
The else branch handles the case when the file does not exist, ensuring the script always prints a clear message, demonstrated in steps 5 and 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'filename' after step 1?
Aundefined
B"test.txt"
C"filename"
Dempty string
💡 Hint
Check the variable_tracker table under 'After Step 1' for 'filename'.
At which step does the script print 'File exists'?
AStep 4
BStep 2
CStep 5
DStep 6
💡 Hint
Look at the 'Output' column in the execution_table for the message 'File exists'.
If the file does not exist, which step shows the printed output?
AStep 3
BStep 4
CStep 6
DStep 5
💡 Hint
Check the execution_table rows where the output is 'File does not exist'.
Concept Snapshot
File existence check in bash:
Use [ -e "$filename" ] to test if a file exists.
If true, run commands in then-block.
Else, run commands in else-block.
Always quote variables to handle spaces.
Print messages to confirm existence.
Full Transcript
This script sets a variable 'filename' to 'test.txt'. It then checks if this file exists using the condition [ -e "$filename" ]. If the file exists, it prints 'File exists'. Otherwise, it prints 'File does not exist'. Quoting the variable ensures the check works even if the filename has spaces or is empty. The script ends after printing the appropriate message.