<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Linux &#124; egrep &#187; Scripting</title>
	<atom:link href="https://www.linuxegrep.com/category/script/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.linuxegrep.com</link>
	<description>Extended search for information</description>
	<lastBuildDate>Tue, 08 Jan 2019 06:23:44 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.2</generator>
		<item>
		<title>Easy commandline argument parsing in shell script</title>
		<link>https://www.linuxegrep.com/archives/script/shellscript/easy-commandline-argument-parsing-in-shell-script/</link>
		<comments>https://www.linuxegrep.com/archives/script/shellscript/easy-commandline-argument-parsing-in-shell-script/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 14:34:39 +0000</pubDate>
		<dc:creator>meharo</dc:creator>
				<category><![CDATA[Shell Scripting]]></category>
		<category><![CDATA[argument]]></category>
		<category><![CDATA[commandline]]></category>

		<guid isPermaLink="false">http://www.findlinuxhelp.com/?p=195</guid>
		<description><![CDATA[Here is a fairly easy method which can parse all input arguments passed to a shell script in commandline. This block of code can be either included in top of the script or source it from an external file. Using this code within a shell script is very simple, just needs to define a global [...]]]></description>
				<content:encoded><![CDATA[<p>Here is a fairly easy method which can parse all input arguments passed to a shell script in commandline. This block of code can be either included in top of the script or source it from an external file.</p>
<p>Using this code within a shell script is very simple, just needs to define a global variable named <span style="color: #ff6600;"><span style="font-family: courier new,courier;">ARGS_INPUT_FORMAT</span></span> and set appropriate values to it. The argument parsing code will read this variable and set appropriate inputs as well as outputs.</p>
<p>Set values to the variable <span style="color: #ff6600;"><span style="font-family: courier new,courier;">ARGS_INPUT_FORMAT</span></span> as shown below.</p>
<p><span id="more-195"></span></p>
<pre lang="text">ARGS_INPUT_FORMAT="OPTION STRING 1|OPTION STRING 2(OPTIONAL)|OPTION STRING N(OPTIONAL):VARIABLE NAME WHICH HOLDS OPTION VALUE:DEFAULT OPTION VALUE(OPTIONAL):DEFAULT OPTION VALUE IF USED AS SWITCH(OPTIONAL)"</pre>
<h2>Example Usage</h2>
<p>These are some examples:</p>
<pre lang="text">ARGS_INPUT_FORMAT="--ignore-case|-i:check_case:NO:YES"
ARGS_INPUT_FORMAT="--user|-u|-U:username:-1:-1,--ignore-case|-i:ignore_case:NO:YES"
ARGS_INPUT_FORMAT="--color:bgcolor"</pre>
<p>Some example script usages are:</p>
<pre lang="text">./main-script.sh --ignore-case="YES"
./main-script.sh -i -u "Find Linux Help"
./main-script.sh --color="Yellow"</pre>
<p>Now access the value of color using variable <span style="color: #ff6600;"><span style="font-family: courier new,courier;">bgcolor</span></span> as shown below.</p>
<pre lang="text">echo "You have chosen $bgcolor color."</pre>
<p>There are some advantages of this code; it is not utilizing the capabilities of an external binary but parse using shell script itself. It never shifts or alters the original arguments supplied to main script. It retains the position and count of arguments and can be re-used them inside the main script again.</p>
<h2>Argument Parsing Code</h2>
<pre lang="text">for arg_opts in $(echo "$ARGS_INPUT_FORMAT" | tr "," " ") ; do
  opt_names=$(echo "$arg_opts" | cut -d':' -f1)
  opt_var=$(echo "$arg_opts" | cut -d':' -f2)
  opt_def_val=$(echo "$arg_opts" | cut -d':' -f3)
  opt_switch_val=$(echo "$arg_opts" | cut -d':' -f4)
  eval "$opt_var=$opt_def_val"
  for opt_name in $(echo "$opt_names" | tr "|" " ") ; do
    arg_pos=1
    while [ $arg_pos -le $# ] ; do
      case "$(eval "echo $$arg_pos")" in
        "$opt_name="*)
              eval "$opt_var="$(echo "$(eval "echo $$arg_pos")" | sed 's/^'"$opt_name"'=//')""
              ARGS_STAT[$arg_pos]=0
              ;;
        "$opt_name")
              if [ $(expr $arg_pos + 1) -le $# ] &amp;&amp; [ $(echo "$(eval "echo $$(expr $arg_pos + 1)")" | grep -c '^-') -eq 0 ] ; then
                ARGS_STAT[$arg_pos]=0
                arg_pos=$(expr $arg_pos + 1)
                eval "$opt_var="$(eval "echo $$arg_pos")""
              else
                eval "$opt_var="$opt_switch_val""
              fi
              ARGS_STAT[$arg_pos]=0
              ;;
        "$opt_name"*)
              eval "$opt_var="$(echo "$(eval "echo $$arg_pos")" | sed 's/^'"$opt_name"'//')""
              ARGS_STAT[$arg_pos]=0
              ;;
        *)
              [ -z "${ARGS_STAT[$arg_pos]}" ] &amp;&amp; ARGS_STAT[$arg_pos]=1
              ;;
      esac
      arg_pos=$(expr $arg_pos + 1)
    done
  done
done</pre>
<p>Download the script file: [download id="5"]</p>
<h2>Script Usage</h2>
<p>Define a global variable as <span style="color: #ff6600;"><span style="font-family: courier new,courier;">ARGS_INPUT_FORMAT</span></span> and set an appropriate value as shown above. Define this variable on top of the main script.</p>
<p>Save the argument parsing script to an external file and source it into the main script. The same source script can be included in as many scripts wherever  you need argument processing. Even the code block can be directly pasted below the global variable definition inside your main script for better portability.</p>
<h2>About Debugging</h2>
<p>The script initializes an array variable named <span style="color: #ff6600;"><span style="font-family: courier new,courier;">ARGS_STAT</span></span> and set debug values to it. If it finds an invalid argument in commandline, the corresponding array index is updated with a dirty flag &#8220;1&#8243;.</p>
<p>Here is a sample code which can be included in the main script to display invalid arguments supplied and their respective position numbers.</p>
<pre lang="text">echo "**Invalid args**"
count=1
while [ $count -le $# ] ; do
  if [ ${ARGS_STAT[$count]} -eq 1 ] ; then
    echo "$(eval echo $$count) ($count)"
  fi
  count=$(expr $count + 1)
done
</pre>
<p>Download the script file: [download id="6"] </p>
]]></content:encoded>
			<wfw:commentRss>https://www.linuxegrep.com/archives/script/shellscript/easy-commandline-argument-parsing-in-shell-script/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: enhanced

 Served from: linuxegrep.com @ 2026-05-07 11:42:13 by W3 Total Cache -->