010-150 · Question #63
The output of the program date should be saved in the variable actdat. What is the correct statement?
The correct answer is A. actdat=`date`. To capture the output of a command into a shell variable, command substitution must be used - either backtick syntax or $().
Question
The output of the program date should be saved in the variable actdat. What is the correct statement?
Options
- Aactdat=
date - Bset actdat='date'
- Cdate | actdat
- Ddate > $actdat
- Eactdat=date
How the community answered
(30 responses)- A70% (21)
- B17% (5)
- C3% (1)
- D3% (1)
- E7% (2)
Why each option
To capture the output of a command into a shell variable, command substitution must be used - either backtick syntax or `$()`.
Backtick syntax (`` actdat=`date` ``) is command substitution, which executes `date` and assigns its standard output as a string to the variable `actdat`. This is one of the two valid forms of command substitution in POSIX shell (the other being `actdat=$(date)`).
`set actdat='date'` uses single quotes, so `date` is treated as a literal string, not executed; `set` also does not assign named variables this way.
`date | actdat` attempts to pipe the output of `date` to a command named `actdat`, which is not a valid command.
`date > $actdat` redirects the output of `date` to a file whose name is the current (likely empty) value of `$actdat`, rather than assigning the output to the variable.
`actdat=date` assigns the literal string `date` to the variable, not the output of the `date` command.
Concept tested: Shell command substitution to capture command output
Source: https://www.gnu.org/software/bash/manual/bash.html#Command-Substitution
Topics
Community Discussion
No community discussion yet for this question.