Getting command output in variables

We can get command output in variables using command substitution. For example, to assign the output of the whoami command to the myusername variable, we could use the following:

$ myuser="$(whoami)"
$ printf '%s\n' "$myuser"
bashuser

Don't forget to use double quotes around the expansion, so that special characters, such as spaces and asterisks, don't get treated specially by the shell.

Command substitution has the special property of trimming trailing newlines from the output of the command it executes. The whoami command actually prints the current username, followed by a newline. Command substitution removes that trailing newline. This is simply for convenience, as the trailing newline is usually not wanted.

Command substitutions can be nested, but note that the double quotes are still required even on the inner expansion to suppress unwanted expansion:

$ mypwent="$(getent passwd "$(whoami)")"
Especially in older shell scripts, you may sometimes see backticks (`) used for command substitution. Bash still allows this syntax so that older scripts can run, but you should prefer the $(command) syntax to `command`; the former is easier to read, and much easier to perform expansions within expansions.