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 ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.