102-500 practice question 16 of 30

Which of the following commands puts the output of the command date into the shell variable mydate?

Full set: 233 questions
Answer options
A: mydate="$(date)" Correct answer
B: mydate="exec date"
C: mydate="$((date))"
D: mydate="date"
E: mydate="${date}"
Correct Answer:
A. mydate="$(date)"
Explanation

To capture the output of a command and assign it to a variable, Bash uses command substitution. The modern and recommended syntax for command substitution is $(command). The shell executes the command within the parentheses and substitutes its standard output in its place. The statement mydate="$(date)" executes the date command, captures its output, and assigns it to the shell variable mydate.

Why Incorrect

B. This assigns the literal string "exec date" to the variable mydate, not the output of the date command.
C. The $((...)) syntax is for arithmetic expansion, not command substitution. It would cause a syntax error with date inside.
D. This assigns the literal string "date" to the variable mydate, rather than executing the command.
E. The ${...} syntax is for parameter expansion, which retrieves the value of a variable named date, not for executing a command.

References

1. GNU Bash Manual, Section 3.5.4 "Command Substitution". It describes the $(command) syntax, stating, "Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standard output of the command".

2. The Open Group Base Specifications Issue 7, 2018 edition, IEEE Std 1003.1-2017, Section 2.6.3 "Command Substitution". This standard defines the $(command) syntax for POSIX-compliant shells.

Scroll to Top