Skip to content

Instantly share code, notes, and snippets.

@MoserMichael
Created June 12, 2026 09:06
Show Gist options
  • Select an option

  • Save MoserMichael/df7419d4d1e60090cc52d2fca13e4b1f to your computer and use it in GitHub Desktop.

Select an option

Save MoserMichael/df7419d4d1e60090cc52d2fca13e4b1f to your computer and use it in GitHub Desktop.
bash_goodies
# -------------------------
# Bash stuff
# -------------------------
Never understood arrays in bash (even though they were added in bash2.0 - 2009)
This explains them:
(can you compare bash to perl5?
No, when declaring a data structure in bash, then you cannot nest a map inside an array or map.
Also runs slower - bash interpreted line by line, instead of bytecode translation/execution of perl5
)
# you don't need to declare arrays with integer keys before use (but you do for hash maps/associative arrays)
# fun part: keys can have gaps and there is 'index out of range'
$ b[0]=1
$ b[2]=2
# shows all values (but it doesn't show, which keys are set...)
$ echo "${b[@]}"
1 2
# this sets the set key values!
$ echo "${!b[@]}"
0 2
# show number of set entries in array - sort of like len(arr) in python
$ echo "${#b[@]}"
2
# access a an entry by index
$ echo "${b[0]}"
1
# this guy is not set, the array can have gaps!
$ echo "${b[1]}"
$ echo "${b[2]}"
2
# assign an arrays with a bunch of values
$ c=(1 2 3 4 5 6)
# iterate over the assigned array
$ for x in ${c[@]}; do echo $x; done
1
2
3
4
5
6
# show first element
$ echo ${c[0]}
1
# show the whole array
$ echo ${c[@]}
1,2,3,4,5,6
# and you can have slices too!
$ echo ${c[@]:2}
3 4 5 6
$ echo ${c[@]:1:2}
2 3
$ echo ${c[@]:1:3}
2 3 4
# -----
Since bash 4.0 (released in 2009) we have hash maps in bash! almost a complete perl5...
--
# Initialize the empty map
#declare -A my_map
# Initialize a map with some values (note: you need to have my_map=( without spaces!)
declare -A my_map=(
['Star']='cat'
['Chucha']='cat'
)
# Add or update key-value pairs
my_map['Michael']='Moser'
echo "Michael maps to ${my_map['Michael']}"
echo "Iterate over key-value pairs"
for user in "${!my_map[@]}"; do
role="${my_map[${user}]}"
echo "User: $user | Role: $role"
done
echo "It is not an error to access nonexisting key - returns empty string"
echo "${my_map['nonexist']}"
# check if key exists
if [[ -v my_map['Star'] ]]; then
echo "key Star exists in map my_map"
fi
# Delete a key-value pair
unset my_map[role]
--
# -------------------------
# didn't know that:
# in bash:
# |&
# is the same as
# 2>&1 |
$ cat no-such-file.txt | grep 'No such file' | wc -l
cat: no-such-file.txt: No such file or directory
0
$ cat no-such-file.txt 2>&1 | grep 'No such file' | wc -l
1
$ cat no-such-file.txt |& grep 'No such file' | wc -l
1
# - useless stuff, it is easy to mix up |& with &|
$ - the second one runs the command in the background.
# - better do 2>&1 |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment