Arrays
arr=()
Create an empty array
arr=(1 2 3)
Initialize array
${arr[2]}
Retrieve third element
${arr[@]}
Retrieve all elements
${!arr[@]}
Retrieve array indices
${#arr[@]}
Calculate array size
arr[0]=3
Overwrite 1st element
arr+=(4)
Append value(s)
str=$(ls)
Save ls output as a string
arr=( $(ls) )
Save ls output as an array of files
${arr[@]:s:n}
Retrieve n elements starting at index s
#!/bin/bash
list=( $(ls) )
echo -e "${list[0]}"
echo -e "${list[1]}"
echo -e "${list[2]}"
echo -e "${list[@]}"#!/bin/bash
declare -a arrPics
for file in *.jpg
do
arrPics=(${arrPics[*]} "$file")
done
# Using [@]
echo -e '\nUsing [@] -----------------------------------'
for item in "${arrPics[@]}"
do
echo "ITEM: *** $item ***"
done
# Using [*]
echo -e '\nUsing [*] -----------------------------------'
for item in "${arrPics[*]}"
do
echo "ITEM: *** $item ***"
done
Source
https://delightlylinux.wordpress.com/2017/04/08/put-filenames-in-bash-array/
Last updated