Bash
The ugliest language in the world.
Parse Command Line Arguments
Often we want to parse command line arguments when executing a bash script, to make the script usable on different things.
It’s a typical use case for a command line tool.
Say you want to do something like:
sh exec-something.sh ./something.txt
The variable ./something.txt
will be available in $1
inside of your bash script.
Similarly, if you run:
sh exec-something.sh ./something.txt ./things/something2.txt
There will be two variables available, $1
and $2
.
Parse NAMED Command Line Arguments
Like the above, except when we need to name them…
# sh ./script.sh -t dog -a bruh -f 123
while getopts t:a:f: flag
do
case "${flag}" in
t) tag=${OPTARG};;
a) noop=${OPTARG};;
f) noop2=${OPTARG};;
esac
done
Get the current directory
Like node’s __dirname
, bash you do this:
dirname $0
Here, $0
refers to the bash script itself.
Set a variable and concatenate it
e.g., if we’re counting dogs…
NOW=$(date +"%T")
DOG_NUM=$1
echo "$NOW:$DOG_NUM" >> dog-log.txt
Capture the output of a command into a variable
Using these things: $()
ME=$(whoami)
echo "$ME"
Interpolating a Variable in a JSON String
See this stackoverflow answer.
Godsend for portable scripting when debugging.
DATA='{"email":"john4'$(date +"%s")'@italic.com","password":"123456"}'
curl --request POST \
--url https://foobar.com/graphql \
--header 'Content-Type: application/json' \
--data "$DATA"
Last modified: