christian at agile venture bolzano 2019 christian fei's blog

agile developer, clean code connoisseur && testing aficionado

read more about me or what i am doing now

scroll through posts that i wrote

Preferred way of defining flags in bash

written on 2019-08-29 by Christian Fei

#post 

this

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

this