christian fei's blog

agile developer

clean code connoisseur && testing aficionado

read more about me

read some posts that i wrote

building pomodoro.cc

follow me on twitter

connect with me on linkedin

distilling customer feedback at wonderflow

Edit this page on GitHub

Preferred way of defining flags in bash

by Christian Fei

written on Thu Aug 29 2019 00:00:00 GMT+0000 (Coordinated Universal Time)

This is the easiest way I found of defining flags to set variables in a bash script.

let's call this file flags.sh:

#!/bin/bash

while [ ! $# -eq 0 ]
do
	case "$1" in
		--name | -n)
			NAME="$2"
			;;
		--id)
			ID="$2"
			;;
    # etc
	esac
	shift
done

This way I can source the file flags.sh and have the variables $NAME and $ID available, like this:

in main.sh

#!/bin/bash

source flags.sh

echo "NAME: $NAME"
echo "ID: $ID"

Awesome, right!? The same for functions (you get the point)

in functions.sh

#!/bin/bash

function print_name {
  echo "NAME: $1"
}

and again, in main.sh:

#!/bin/bash

source flags.sh
source functions.sh

print_name $NAME