Parsing script parameters

Quick and dirty parsing procedure for unix shell scripts


parse_command_line ()
{
typeset -i user_opt help_opt password_opt verbose_opt
typeset errmsg

arg_cou=$#

while [ "$#" -gt 0 ]
do
case "$1" in
-@([U]) ) let user_opt=user_opt+1 ;;
-P ) let password_opt=password_opt+1 ; ask_pass=0 ;;
-option1 ) ;;
-option2 ) ;;
-option3 ) ;;
-@([hH?])) help_opt=1;;
-v*(erbose)) let verbose_opt=verbose_opt+1 ;;
*)
if [ user_opt -eq 1 ];then
USER="$1"; user_opt=0
elif [ password_opt -eq 1 ];then
PASS="$1"; password_opt=0
elif [ verbose_opt -eq 1 ];then
verbose_level="$1"; verbose_opt=0
else
### help_opt=1
CMD=$* ; break
fi
;;
esac
shift
done

if [ arg_cou -eq 0 ] ; then
help_opt=1 ; errmsg="Nothing to do"
fi

for opt in user password ; do
if [ ${opt}_opt -ne 0 ] ; then
help_opt=1 ; errmsg="${errmsg}\n${opt} is absent"
fi
done

if [ verbose_opt -ne 0 ] ; then
verbose_level=$verbose_opt
fi

if [ help_opt -eq 1 ]; then
help "$errmsg"
fi
}

Rev function and comma-separated output

Here is the shell command snippet to display comma-separated output:

ls -lrt | rev | sed 's/\\([0-9][0-9][0-9]\\)/\\1,/g' | rev | sed 's/\\([\^0-9]\\),\\([0-9]\\)/\\1\\2/g;s/\^,\\([0-9]\\)/\\1/g'
Example:
-rw-r—– 1 sybase dba 1,572,872,192 Feb 2 07:09 master.dbf

Rev in awk

#!/bin/ksh
nawk '{ l=length($0) ; for(i=l;i>0;i--) { printf "%s", substr($0,i,1) } ; print "" }'

Rev function (absent on SunOS) :

(Warning! Avoid spaces before #define – SunOS cc compiler doesn’t like them)


#include <stdio.h>
#ident "@(#)rev 1.0 02/01/2006"
#define MAX_STRING_SIZE 2000char version[] = "rev v1.0 02/01/2006";

main(argc,argv)
int argc;
char *argv[];
{
char my_src[MAX_STRING_SIZE] ;
char my_dst[MAX_STRING_SIZE] ;
char *retCode ;

char *tmp_s ;
int i;

char *filename;
FILE *fSource ;

/* check command line arguments */
if (argc > 1) {
if( argv[1][0]=='-' || argv[1][0]=='/' ) {
fprintf(stderr, "Usage: %s [file] \n", argv[0]);
exit(1);
}
filename=argv[1] ;
fSource = fopen( filename, "r" ) ;
if ( fSource == NULL ) {
fprintf(stderr, "Can't open %s for reading\n", filename );
exit(1);
}
} else {
/* Using the standard input */
fSource=stdin ;
} /* if (argc > 1) */

while( (retCode = fgets( my_src, MAX_STRING_SIZE, fSource ) )!=NULL ) {

tmp_s=my_dst+MAX_STRING_SIZE-1;
*tmp_s=0;

for( i=0 ; i < MAX_STRING_SIZE && my_src[ i ] != 0 ; i++ ) {
if( my_src[ i ] == '\n' ) {
continue ;
}
tmp_s--;
*tmp_s=my_src[ i ];
}

fprintf( stdout, "%s\n", tmp_s);
}

fclose( fSource ) ;

fflush( stdout );

exit(0);
} /* main */