Aqui está uma resposta longa. Este é um template que eu uso no trabalho (iniciado no ksh mas funciona no bash).
Não funcionará para fazer "-paj a_arg j_arg", mas você provavelmente poderia modificá-lo para funcionar dessa maneira. Confira as linhas paramnum
.
#!/bin/bash
# Filename:
# Location:
# Author:
# Startdate:
# Title:
# Purpose:
# DEFINE FUNCTIONS
usage() {
echo "usage: SCRIPTNAME [-us]"
}
isflag() {
# input: $1=word to parse
# returns: TRUE if $1 starts with a dash.
retval=0
if [[ $1 = --* ]] ;
then
# long-name flag
retval=2
elif [[ $1 = -* ]] ;
then
# params to split
retval=1
fi
echo $retval
}
function parseParam {
# determines if --longname or -shortflagS that need individual parsing
trimParam=$(echo $param|sed -n 's/--//p')
if [ ! -z "$trimParam" ];
then
parseFlag $trimParam
else
splitShortParams
fi
}
function splitShortParams {
i=2
while (( i <= ${#param} ))
do
char=$(expr substr "$param" $i 1)
parseFlag $char
(( i += 1 ))
done
}
function parseFlag {
flag=$1
hasval=0
case $flag in
# INSERT NEW FLAGS HERE
#"v" | "verbose") verbose=1;; # simple flag
"i" | "infile" | "inputfile") getval;infile1=$tempval;;
#"s" | "silent") silent=1;;
"u" | "usage") usage; exit;;
esac
# COMMENT THIS IF NOT DEBUGGING
#if [[ hasval -eq 1 ]];
#then
# echo "flag: $flag = $tempval"
#else
# # goal: cause an error
# echo "flag: $flag"
#fi
}
function getval {
if [ ! -z "$nextparam" ] && [[ $(isflag $nextparam) -eq 0 ]]
then
tempval=$nextparam
hasval=1
paramnum=$nextparamnum
else
#the var should not be changed from blank/default value
tempval=
fi
}
# INITIALIZE VARIABLES
infile1=
outfile1=
today='date '+%Y-%m-%d''
server='uname -n'
# VALIDATE PARAMETERS
# scroll through all parameters and check for isflag.
# if isflag, get all flags listed. Also grab param#.
paramcount=$#
thiscount=0
paramnum=0
while [[ paramnum -lt paramcount ]]
do
paramnum=$((paramnum+1))
eval param=\${$paramnum}
nextparamnum=$((paramnum+1))
eval nextparam=\${$nextparamnum}
case $param in
"-") [ ];; #null flag
esac
if [[ ! -z "$param" ]]
then
# parameter $param exists.
# thisisflag=$(isflag $param)
if [[ $(isflag $param) -gt 0 ]];
then
# IS FLAG
parseParam
else
# IS VALUE
(( thiscount += 1 ))
#echo value: ${param} # COMMENT IF NOT DEBUGGING
#[[ $thiscount = 1 ]] && infile1=${param} #EXAMPLE
fi
fi
done
# CONFIRM TOTAL NUMBER OF PARAMETERS IS CORRECT
#if [[ $thiscount -lt 2 ]];
#then
# echo "Error: fewer than 2 parameters..."
# exit
#fi
# SET VARIABLES TO DEFAULTS IF NOT ALREADY CONFIGURED
#if [[ valuen -eq 0 ]] ; then valuen=15; fi
# MAIN LOOP