1

I am new to unix script. I am trying to create a script that acts as a unix command, such as "ls -l", "ls -la"


myscript -x     ----> do thing 1
myscript -xy    ----> do thing 1, do thing 2
myscript -yz    ----> do thing 2, do thing 3

so, "-x", "-xy" are $0 ? or we need to use different variables to get that?

Thanks

chipbk10
  • 5,783
  • 12
  • 49
  • 85
  • 3
    related: [How do I parse command line arguments in bash?](http://stackoverflow.com/q/192249/4279) – jfs Sep 02 '14 at 14:01
  • See (in addition to the many, *many* other times this has been asked and answered on StackOverflow) BashFAQ #35: http://mywiki.wooledge.org/BashFAQ/035 – Charles Duffy Sep 02 '14 at 14:10

1 Answers1

5

In Bash, arguments starts with index 1, while $0 is reserved to the command itself. This applies to functions and commands as well.

This is how you achieve something similar to what you requested:

while [ "$1" != "" ] ; do
  case "$1" in
    -x)
       do_thing_1
       ;;
    -y)
       do_thing_2
       ;;
    -z)
       do_thing_3
       ;;
    *)
       error $1
       exit -1
       ;;
  esac
  shift
done

You need to declare the functions do_thing_xxx and error.

I said "something similar" because this script will understand "myscript -x -y -z" but detects "myscripts -xyz" as wrong.

To achieve a more complex behavior, like yours, you need to use GETOPT, as explained here: http://wiki.bash-hackers.org/howto/getopts_tutorial

Hope that helps.

HappyCactus
  • 1,935
  • 16
  • 24
  • As `man bash(1)` states, in linux "The getopt command is part of the util-linux package and is available from [link](ftp://ftp.kernel.org/pub/linux/utils/util-linux/). Perhaps you need to install a port. – HappyCactus Sep 02 '14 at 14:33
  • but I see getopts command in terminal. I use your code, but it seems not to detect "-x", "-y" options. It always comes to the last case "*". Another thing is I use [ -z "$1" ] to see whether $1 is empty or not – chipbk10 Sep 02 '14 at 14:44
  • Seems to work nicely on my mac, both with bash and sh. I checked using "echo" as case. – HappyCactus Sep 02 '14 at 15:09