cri.dev
about posts rss

Preferred way of defining flags in bash

Published on

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

Here, have a slice of pizza πŸ•