Bash(and others) things that i use every day
More and more we embrace bash to do things that maybe in the past we used lower level languages (Dockerfiles , Makefiles , Pipelines etc etc), or at least that’s the way im seeing it , so im leaving some bash little things i user every day:
for loops:
for i in $(seq 0 3) ; do echo ${i} ;done
for i in {0..3} ; do echo $i ; done
for i in "a\nb\nc" ; do echo $i ; done
if else oneliners:
[[ $( pgrep nginx | wc -c ) > 0 ]] && echo "nginx running" || echo "nginx running"
[[ $( pgrep nginx | wc -c ) > 0 ]] && echo "nginx running" || { echo "nginx not running" , systemctl start nginx.service ; }
[[ $( pgrep nginx | wc -c ) > 0 ]] && : || { echo "nginx not running" , systemctl start nginx.service ; }
while forever:
while : ; do ss -ton | grep 80 | grep -v ESTAB ; sleep 1; done
while true ; do ss -ton | grep 80 | grep -v ESTAB ; sleep 1; done
bash expansions:
echo ${RANDOM:0:4}
echo $TERM | echo ${TERM/256color/}
merging columns:
cat list | paste - -
cat list | xargs -n 2
dynamic fd:
file <(ss)
vim <(ss)
cat <(ss)
loop line by line instead of word by word
while read l ; do echo ${l} ; done < <( cat list| xargs -n2 )
“-” as fd to stdout
curl [-s --output /dev/null https://www.google.com](https://www.google.com) -c-
nmap [www.google.com](http://www.google.com) -sT -p 80 -oG
Default value for variables
VAR=${VAR:-default}
Arrays and maps
declare -A res
urls=("[www.com.ar](http://www.com.ar)" "[www.facebook.com](http://www.facebook.com)" "[www.twitter.com](http://www.twitter.com)")
for i in ${urls[@]}
do
res[$i]=$(curl -s --output /dev/null $i -c- | base64)
done
for i in ${!res[@]}
do
echo $i
echo ${res[${i}]} | base64 --decode
done
declare -A res (declares a hash/map/dict)
urls=() (declares a list/array)
urls+=(1) (appends to list)
res["test"]="test" (creates a new entry in the map)
${res[@]} (return all values)
${!res[@]} (returns all keys)