Preferred way of defining flags in bash

by Christian Fei @ 2019-08-29

85 words, 1 minute reading time

#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

Leave a comment

Better web scraping with node.js My blogging stack in 2020 Run cypress integration tests with github actions workflow Simple telegram message with github actions Deploy eleventy site with github actions on aws s3 Simple ad and trackers blocking with dns Build for a slow connection Upgrade mongodb 3 to 4 on ubuntu Publishing org scoped npm packages with travis A story about npm publish / unpublish