0

I am writing a script which will intercept any command I fire on my shell (ksh93), and process the options and arguments according to my requirement.

Say, I have script.ksh

./script.ksh
$ rm -rf dir1 dir2

Then I want to extract r,f and dir1, dir2 separately, so that I can examine each option individually and then do something more before deleting dir1, dir2

I came up with the following code to separate options and arguments into different arrays:

read INPUT

count=`echo $INPUT | wc -w`
echo $count

command=`echo $INPUT | cut -d' ' -f1`
echo $command

counter=2
indexOptions=0
indexArgs=0
while [ "$counter" -le "$count" ]
do
    word=`echo $INPUT | cut -d' ' -f$counter`

    if [[ "$word" == -* ]]
    then

        options["$indexOptions"]=$word
        ((indexOptions=indexOptions+1))
    else
        args["$indexArgs"]=$word
        ((indexArgs=indexArgs+1))
    fi
    ((counter=counter+1))
done

But I wish to know if there is a better way or any other command or tool which I can use to improve my approach.

Thanks in advance.

pratz
  • 107
  • 7

1 Answers1

0

You can use getopts. It is newer and IMHO better than getopt, see a question about getopt for some more discussion.

Community
  • 1
  • 1
Walter A
  • 19,067
  • 2
  • 23
  • 43
  • I am not passing arguments to the script, after running the script I will type any command and then from that command I have to extract the options and arguments. I tried looking into the command `getopts` but am not able to do what I need. Maybe it is not obvious to me because I am new to Unix and shell scripting ( 1 month experience ). Could you please nudge me in the right direction? – pratz Aug 19 '15 at 09:11
  • Try and find some examples. Your use case is different from the default in that you will need to provide `$INPUT` as the final argument of `getopts` explicitly. Whenever you read a new command and `$INPUT` changes, you must reset `getopts` with `OPTIND=1`. – Henk Langeveld Aug 19 '15 at 10:45