A system administrator is writing a shell script that must prompt a user for a file name and then efficiently read only the first line of that file into a variable. Which of the following commands is the most efficient and idiomatic method to achieve this in Bash?
read -p "Enter the file name: " file; line=$(cat "$file" | head -n 1)
read -p "Enter the file name: " file; IFS= read -r line <<< "$file"
read -p "Enter the file name: " file; IFS= read -r line < "$file"
read -p "Enter the file name: " file; IFS= read -r line <<< $(cat "$file")
The correct option is read -p "Enter the file name: " file; IFS= read -r line < "$file". This approach is the most efficient. The read -p command prompts the user and captures the file name. Then, IFS= read -r line < "$file" uses the shell's built-in read command with input redirection (<). This method is highly efficient because it reads only the first line from the file without starting external processes. Using IFS= prevents trimming of leading/trailing whitespace, and -r prevents backslash interpretation.
The option using cat $file | head -n 1 works, but it is less efficient as it creates two external processes (cat and head) and a pipe.
The option with <<< $(cat $file) is also inefficient because it uses an unnecessary cat process and reads the entire file's content into a temporary string before read processes it.
The option using <<< "$file" is incorrect. A here-string (<<<) provides the literal string that follows it as standard input; it does not read from a file path. This command would cause the variable line to contain the file's name, not its content.
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=` do in the Bash script?
Open an interactive chat with Bash
Why is the `-r` option used with the `read` command?
Open an interactive chat with Bash
Why is input redirection (`<`) more efficient than using `cat`?