Linux/Unix: Assigning multiple variables from the command output

📄 Wiki page | 🕑 Last updated: Oct 20, 2022

In modern shells like bash and zsh, you can use the built-in read command to read multiple variables from the command output:

read d m y <<< $(date +'%d %m %Y')

If you now run echo $d $m $y, you should see something like this:

20 10 2022

How does it work?

First, we're telling read to read three variables: d, m, and y from stdin (standard input):

read d m y

If we'd try to execute this in an interactive shell and enter 20 10 2022, we'd get the same result as above.

Next, we want to redirect the output of the date command to the read's input. A common mistake here is to try to use pipe redirection:

date +'%d %m %Y' | read d m y

This wouldn't work because read is executed in a subshell. It will actually read and assign variables, but those variables will be lost once the command completes and the subshell exits.

So, instead, we're using a dynamically generated heredoc string (<<<), i.e.:

read d m y <<< "20 10 2022"

Is equivalent to:

read d m y <<< $(date +'%d %m %Y')

This should work in modern shells like bash and zsh.

Alternative: eval

We could also use eval for this purpose:

eval $(date +"d=%d; m=%m; y=%Y")

The result will be the same, but as always with eval, be very careful if you're dealing with any untrusted input.

Ask me anything / Suggestions

If you have any suggestions or questions (related to this or any other topic), feel free to contact me. ℹī¸

If you find this site useful in any way, please consider supporting it.