Wednesday, July 04, 2012

Parse Command Line Options in Bash Script

This is an example of how to use getopts to parse command line options in bash
#!/usr/bin/env bash
LIST_FILE=0
RECURSIVE=0
# parse options from command line 
while getopts l:r: OPT; do
    case "$OPT" in
        r)  RECURSIVE="$OPTARG";;
        l)  LIST_FILE="$OPTARG";;
      [?])  echo "Usage: $0 [OPTION] [ARGS]">&2; exit 1;;
    esac
done
# shift parsed options
shift `expr $OPTIND - 1`
# process the arguments
for file in "$*"; do
    echo $file
done

No comments:

Post a Comment