A system administrator needs to write a shell script that prompts the user for a file name and then reads a single line from that file. The goal is to store this line in a variable for further processing. Which of the following options achieves this while making sure the script asks for the file name and reads only the first line of the provided file?
You selected this option
read -p "Enter the file name: " file; IFS= read -r line < "$file"
You selected this option
read -p "Enter the file name: " file; line=$(cat $file | head -n 1)
You selected this option
read -p "Enter the file name: " file; IFS= read -r line <<< $(cat $file)
You selected this option
read -p "Enter the file name: " file; IFS= read -r line <<< "$file"
The correct answer is 'read -p "Enter the file name: " file; IFS= read -r line < "$file"' because the '-p' option allows the script to prompt the user with a message and read input into the 'file' variable. Then, 'IFS= read -r line < "$file"' is used to read the first line from the file specified by the user into the variable 'line'; 'IFS=' prevents leading/trailing whitespace from being trimmed, and '-r' prevents backslashes from being interpreted as escape characters. The '< "$file"' syntax redirects the contents of the file into the read command. Options B and C are incorrect because they attempt to use 'cat', which is unnecessary and will not properly assign the first line to the variable 'line'. Option D is incorrect because '<<<' is not the correct way to redirect file content to 'read'.
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 'IFS=' mean in a shell script?
Open an interactive chat with Bash
What does the '-r' option do in the 'read' command?
Open an interactive chat with Bash
Why is using '<' with 'read' a better option than using 'cat'?