brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ${arr[@]:1:2} takes a slice out of a bash array

Bash
~/tips/tip-bash-array-slice

a=(a b c d e)

Get some elements of an array, like all but the first, without a loop.

Splitting a list into its first item and the rest comes up all the time, for example a subcommand followed by its arguments. Bash slices arrays with the same syntax it uses for strings.

Give a start index and, optionally, a count:

a=(a b c d e)
echo "${a[@]:1:2}"   # b c
echo "${a[@]:2}"     # c d e
echo "${a[@]: -2}"   # d e

The last one counts from the end. The space before -2 is needed; without it bash reads :- as the default value syntax and you get the whole array.

In a script I’d use it to split the arguments:

args=("$@")
cmd=${args[0]}
rest=("${args[@]:1}")
echo "running $cmd with ${#rest[@]} arguments"

With the quotes around "${args[@]:1}", names with spaces stay whole.

The numbers are positions in the list, not real index numbers. After an unset that left a hole in the array, the result can surprise you, so rebuild the array with a=("${a[@]}") first if you have removed elements. For the positional parameters themselves, "${@:2}" works directly without copying them into an array.

Further reading: Bash manual: Shell Parameter Expansion

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link