LFCS · Question #746
Which of the following is the output when the below shell script executes? cat <<foobar Hello foobar foobar
The correct answer is D. Hello foobar. The cat << foobar construct is a 'here document', which reads input until the specified delimiter (foobar) is encountered on a line by itself.
Question
Options
- AThe contents of the file foobar.
- BHello
- CNo output but a file named foobar is created.
- DHello foobar
- EHello foobar foobar
How the community answered
(23 responses)- B4% (1)
- C9% (2)
- D87% (20)
Why each option
The `cat << foobar` construct is a 'here document', which reads input until the specified delimiter (foobar) is encountered on a line by itself.
This is a here document, not a command to display the contents of a file named `foobar`.
This would be the output if the delimiter was `foobar` but the second `foobar` was omitted or part of the output.
`cat` with a here document prints to standard output, it does not create a file by default.
In a here document (`cat <<foobar`), `cat` reads all lines as standard input until it encounters the delimiter `foobar` on a line by itself. The input includes "Hello" and the first "foobar" on the subsequent line, with the final "foobar" acting as the delimiter itself, thus only "Hello foobar" is printed.
The final `foobar` on its own line acts as the delimiter, signaling the end of input, and is therefore not printed as part of the content.
Concept tested: Shell here document syntax
Source: https://learn.microsoft.com/en-us/azure/cloud-shell/persisting-home-directory#use-a-here-document
Topics
Community Discussion
No community discussion yet for this question.