010-160 · Question #61
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`. Command substitution using backticks captures the stdout of a command and assigns it to a shell variable.
Question
Options
- Aactdat=
date - Bset actdat=
date - Cdate > $actdat
- Ddate > $(actdat)
- Eactdat=date
How the community answered
(21 responses)- A90% (19)
- B5% (1)
- C5% (1)
Why each option
Command substitution using backticks captures the stdout of a command and assigns it to a shell variable.
Wrapping date in backticks performs command substitution, executing the date command and assigning its stdout output to actdat. This is the classic POSIX-compatible syntax; the modern equivalent is actdat=$(date). Both forms replace the expression with the command's output before the assignment occurs.
The set builtin modifies shell options or positional parameters, not named variable assignments; set actdat=`date` is invalid syntax for variable assignment.
The > operator redirects output to a file; date > $actdat would write to a file whose name is the current value of actdat, not store date's output in the variable.
$(actdat) is command substitution that attempts to execute actdat as a command, not a redirection of date's output into a variable.
actdat=date assigns the literal string 'date' to the variable rather than the output of running the date program.
Concept tested: Shell command substitution assigning output to variable
Source: https://www.gnu.org/software/bash/manual/bash.html#Command-Substitution
Topics
Community Discussion
No community discussion yet for this question.