paperlined.org
apps > bash
document updated 11 days ago, on Nov 22, 2024

command substitution in Bash

Command substitution captures the output of one command, and sends it to another. A basic example:

echo "On next Friday, the date will be $( date --date='09:00 next fri' )!"

splitting the output

Bash will split up the output of command-substitution, allowing you to, for example, pass a list of filenames out:

grep -i error $( ls -rt /var/log/m* )

Unfortunately it always 1) does wildcard expansion, and 2) splits on spaces and newlines, so it will break if any filenames contain spaces or wildcards. To solve this limitation, use readarray AKA mapfile:

readarray -t files < <( ls -rt /var/log/m* )

grep -i error "${files[@]}"


# utility -- display the exact contents of the array
perl -le'print qq["$_"]for@ARGV'   "${files[@]}"