Quick and Dirty Way to Parse Command Line in a Bash Script

The Problem

I want a quick and dirty way to parse command line from my bash script. For example:

	myscript.sh --file foo.txt --width 72

The Solution

The method is truly quick and dirty, but before we dive right in, let’s make a few assumptions:

  • Each flag must be followed by a value. That means –debug 1 is fine, but –debug is not
  • The flag name will become the variable name. For example, –file foo.txt will result in a variable $file which has value foo.txt
  • The function does not check or validate the variables in any way. It’s a GIGO (garbage in, garbage out) situation
  • Flags can have one- or two-dash: -debug is the same as –debug

With that in mind, let’s take a look at the function

# file: getopt_simple.sh
function getopt_simple()
    until [ $# -eq 0 ]
        eval ${1##*-}='$2'
        shift 2

Below is a sample script which make use of this function


# file: getopt_simple_tryout
# Try out the simple getopt function

# Include the function
source getopt_simple.sh

# Simulate the command line
set -- --file myfile.txt -depth 3 -width 72 --name "Hai Vu"

# Parse the command line
getopt_simple "$@"

# Now show the variables
echo "file  = $file "
echo "depth = $depth"
echo "name  = $name "

Here is its output:

	$ getopt_simple_tryout.sh 
	file  = myfile.txt 
	depth = 3
	name  = Hai Vu 


  • Line 4: Loop until we exhaust the parameters on the command line
  • Line 6: The ${1##*-} expression strips the preceding dashes (-) from $1. We treats $1 as the name of the variable and $2 as its value
  • Line 7: Move to the next pair of parameters


This function does not do any checking or validation at all, but it is short and sweet–good for those times when you need to try something out quickly


3 thoughts on “Quick and Dirty Way to Parse Command Line in a Bash Script

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s