Please enable JavaScript eh!

 ⌘ Web Mechanic ⌘ 

Bash Scripting


Command Substitution

This allows the output of a command to be substituted by a variable. Another very handy and useful operation.

We use it similarly to parameter expansion, except with parentheses instead of braces.

$(command)

Or we can also enclose the command in back-ticks (`):
NOTE: these are NOT apostrophes

`command`

A tyro example:

echo $(whoami)
trudge

To get the output into a variable:

Moi=$(whoami)
echo "My login is: $Moi"
echo
You=`whoami`
echo "But you are also $You!"
echo

Array Population

In the page on arrays, we mentioned populating an array using a loop.

While that method will work if the element values are known, many times a programmer may not have this information. S/he must rely on a command substitution for that.

The accepted method of getting results of a command into an array is the mapfile command.

echo "Using 'mapfile' to populate an array:"
MyFiles=()
mapfile -t MyFiles < <(ls ~/httpd/bash/*.jpg )
for file in "${MyFiles[@]}"; do
	printf "%s\n" "$file"
done
/Users/trudge/httpd/bash/101.1.jpg
/Users/trudge/httpd/bash/103.1.jpg
/Users/trudge/httpd/bash/104.1.jpg
/Users/trudge/httpd/bash/104.2.jpg
/Users/trudge/httpd/bash/104.3.jpg
/Users/trudge/httpd/bash/104.4.jpg
/Users/trudge/httpd/bash/105.1.jpg
/Users/trudge/httpd/bash/105.2.jpg
/Users/trudge/httpd/bash/105.3.jpg
/Users/trudge/httpd/bash/MyHome.jpg
/Users/trudge/httpd/bash/background.jpg
/Users/trudge/httpd/bash/colors1.jpg
/Users/trudge/httpd/bash/colors2.jpg
/Users/trudge/httpd/bash/colors3.jpg
/Users/trudge/httpd/bash/expand-mkdir.jpg
/Users/trudge/httpd/bash/filing.jpg

The mapfile command (AKA readarray) can be used in a couple of different ways:

There are some options available as well:

We used the -t option above when running the ls command.

Here we use the -n option:

mapfile -n 10 webBash< <(ls -l ~/httpd/bash/*.jpg)
printf "%s" "${webBash[@]}"

-rw-r--r--  1 trudge  staff   12993 Aug 25 16:32 /Users/trudge/httpd/bash/101.1.jpg
-rw-r--r--  1 trudge  staff   12993 Aug 25 16:32 /Users/trudge/httpd/bash/103.1.jpg
-rw-r--r--  1 trudge  staff   18787 Aug 25 17:30 /Users/trudge/httpd/bash/104.1.jpg
-rw-r--r--  1 trudge  staff   39757 Aug 28 15:27 /Users/trudge/httpd/bash/104.2.jpg
-rw-r--r--  1 trudge  staff   84021 Aug 28 15:37 /Users/trudge/httpd/bash/104.3.jpg
-rw-r--r--  1 trudge  staff  319414 Aug 28 15:52 /Users/trudge/httpd/bash/104.4.jpg
-rw-r--r--  1 trudge  staff   19219 Aug 29 11:51 /Users/trudge/httpd/bash/105.1.jpg
-rw-r--r--  1 trudge  staff   18867 Aug 29 11:52 /Users/trudge/httpd/bash/105.2.jpg
-rw-r--r--  1 trudge  staff   74527 Aug 29 11:43 /Users/trudge/httpd/bash/105.3.jpg
-rw-r--r--  1 trudge  staff    6249 Sep 11 12:48 /Users/trudge/httpd/bash/MyHome.jpg

All in all, a handy tool to have in your bash toolbox.