LX0-104 · Question #3
Which of the following commands puts the output of the command date into the shell variable mydate?
The correct answer is A. mydate="$(date)". To capture the standard output of a command into a shell variable, command substitution must be used. The $(command) syntax captures the output of command and substitutes it into the variable assignment.
Question
Options
- Amydate="$(date)"
- Bmydate="exec date"
- Cmydate="$((date))"
- Dmydate="date"
- Emydate="${date}"
How the community answered
(51 responses)- A86% (44)
- B6% (3)
- C4% (2)
- D2% (1)
- E2% (1)
Why each option
To capture the standard output of a command into a shell variable, command substitution must be used. The `$(command)` syntax captures the output of `command` and substitutes it into the variable assignment.
The `$(date)` syntax performs command substitution, executing the `date` command and replacing `$(date)` with its standard output. This output is then assigned to the `mydate` variable.
The `exec` command replaces the current shell with the specified command, it does not capture the command's output into a variable.
The `$((expression))` syntax is used for arithmetic expansion, evaluating an arithmetic expression, not for capturing command output.
Assigning `mydate="date"` simply assigns the literal string "date" to the variable `mydate`, it does not execute the `date` command.
The `${{variable}}` syntax is not a standard shell construct for command substitution or variable expansion.
Concept tested: Shell command substitution
Source: https://www.gnu.org/software/bash/manual/bash.html#Command-Substitution
Topics
Community Discussion
No community discussion yet for this question.