A system administrator needs to create a shell script that iterates over user-specified file names and checks if each file exists in the current directory. If the file exists, the script should display the name of the file along with a message stating that it exists. Which of the following script snippets would BEST accomplish this task?
for file in "$@"; do if [ -e "$file" ]; then echo "File $file exists"; fi; done
for file in "$@"; do if [ -e $file_name ]; then echo "File $file found"; fi; done
for file; do if [ -e "$file exists" ]; then echo "The file was found"; fi; done
for file in "$@"; do echo "Checking $file" << if [ -e $file ]; then echo "$file detected"; fi; done
The correct answer is Option A. The for file in "$@"; do ...; done loop correctly iterates over the list of arguments passed to the script. For each iteration, if [ -e "$file" ]; then checks if the current file exists with -e (file exists test operator) and the following echo "File $file exists" statement prints the appropriate message. Double-quoted $file prevents issues with filenames containing spaces or special characters.
Option B is incorrect because it checks if a string literal '$file exists' rather than checking if each file exists. Option C is incorrect as it checks for the variable $file_name which is not defined in the context and also uses incorrect syntax for testing file existence. Option D is incorrect because it uses << redirection operator, which is used to redirect input from a here document and is not a proper way to check for the existence of files.
Ask Bash
Bash is our AI bot, trained to help you pass your exam. AI Generated Content may display inaccurate information, always double-check anything important.
What does the '-e' operator mean in a shell script?
Open an interactive chat with Bash
What is the purpose of using '$@' in a shell script?