The array syntax in bash
is simple, using parentheses (
and )
:
# string
var=name
# NOT array of 3 elements
# delimiter is space ' ' not ,
arr=(one,two,three)
echo ${#arr[@]}
1
# with space
arr=(one two three)
# or ' ',
arr=(one, two, three)
echo ${#arr[@]}
3
# brace expansion works as well
# 10 elements
arr=({0..9})
echo ${#arr[@]}
10
# advanced one
curly_flags=(--{ftp,ssl,dns,http,email,fc,fmp,fr,fl,dc,domain,help});
echo ${curly_flags[@]}
--ftp --ssl --dns --http --email --fc --fmp --fr --fl --dc --domain --help
echo ${#curly_flags[@]}
12
if you want to run a command and store the output
# a string of output
arr=$(ls)
echo ${#arr[@]}
1
# wrapping with parentheses
arr=($(ls))
echo ${#arr[@]}
256
A more advanced / handy way is by using built-in bash commands mapfile
or readarray
and process substitution. here is is an example of using mapfile
:
# read the output of ls, save it in the array name: my_arr
# -t Remove a trailing DELIM from each line read (default newline)
mapfile -t my_arr < <(ls)
echo ${#my_arr[@]}
256