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.

#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;


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.

#!/usr/bin/perl -w

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


Parsing command line arguments in Python

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

import sys

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

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


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.

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
echo ”

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

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