Advanced Bash Scripting: Part 1 🔥
Become a Bash Scripting Ninja 🥷!
4 min readFeb 22, 2024
Hello, World! Do you use command-line frequently? Or find yourself writing scripting Bash often? If your answer is yes, then this blog (more like cheat sheet!) is just what you were looking for because I’ll be providing you with some cool tricks that I’ve learned while diving deeper into the Bash scripting language. Let’s get straight into it!
Special characters and operations
echo ~+ # same as "echo $PWD"
echo ~- # same as "echo $OLDPWD"
echo $* # all positional arguments passed to script, function, etc
echo $@ # same as above
: # means no operation (no-op)
# ternary operator in Bash!
variable=$(( 1>2 ? 1:2 ))
echo $variable
# 2
# get last positional parameter
last_arg=${!#}
echo $last_arg
# ./script.sh 1 2 3 4
# 4
# if `username` not set, set default value to output of `whoami` command
echo ${username:-$(whoami)}
# output of `whoami` command
# if variable is set, use alternative value
path=/some/path
path=${path:+/some/alternative/path}
echo $path
# /some/alternative/path
Generating all the characters for a valid base 64 / hex string
b64_chars=( {a..z} {A..Z} {0..9} + / = )
echo $b64_chars
# a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 + / =…