How to parse command line arguments/parameters in C/C++/Perl/Python/Bash

This is the first of a series of simple posts highlighting programming idioms in several languages.

One of the perils of programming in multiple languages regularly is that I sometimes forget simple things about a language.

This series is intended as a reference for myself and others when switching back and forth between languages.

There are fancy ways to grab options and such in all of these languages.

However, this is the basics.

Parsing command line arguments in c/c++

For c/c++, the first parameter to ‘main()’ is the number of arguments including the program name.

The second parameter is an array with valid indices o to argc-1.

[cpp]
#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
cout << "argc: " << argc << "\n";
for (int i = 0; i < argc; i++)
{
cout << "argv[" << i << "]: " << argv[i] << "\n";
}
return 0;
}
[/cpp]

output:

Parsing command line arguments in Perl

Perl stores all parameters in an array named ‘ARGV’. Be aware that $#ARGV will be -1 when there are no parameters.

[perl]
#!/usr/bin/perl -w

print "\$#ARGV: $#ARGV \n";
foreach $argnum (0 .. $#ARGV) {
print "\$ARGV[$argnum]: $ARGV[$argnum]\n";
}
[/perl]

output:

Parsing command line arguments in Python

Python stuffs all the parameters, including the script name, into an argv array.

[python]
import sys

print(‘number of arguments:%d’ % len(sys.argv))
print(‘using loop’)
i=0
for x in sys.argv:
print("%d:%s" % (i,x))
i += 1

print(”)
print(‘using index’)
for i in range(0, len(sys.argv)):
print("%d:%s" % (i,sys.argv[i]))
[/python]

output:

Parsing command line arguments in Bash

Of course, there are many conventional ways to pull off parameters in bash.
Here are just a few.
Note that ‘$*’ and ‘$#’ don’t work well with parameters that contain spaces.

[bash]
echo ‘number of arguments’
echo "\$#: $#"
echo ”

echo ‘using $num’
echo "\$0: $0"
if [ $# -ge 1 ];then echo "\$1: $1"; fi
if [ $# -ge 2 ];then echo "\$2: $2"; fi
if [ $# -ge 3 ];then echo "\$3: $3"; fi
if [ $# -ge 4 ];then echo "\$4: $4"; fi
if [ $# -ge 5 ];then echo "\$5: $5"; fi
echo ”

echo ‘using $@’
let i=1
for x in $@; do
echo "$i: $x"
let i=$i+1
done
echo ”

echo ‘using $*’
let i=1
for x in $*; do
echo "$i: $x"
let i=$i+1
done
echo ”

let i=1
echo ‘using shift’
while [ $# -gt 0 ]
do
echo "$i: $1"
let i=$i+1
shift
done

[/bash]

output:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">