1

I am new to UNIX scripting so any help is appreciated. I have a basic shell script called test.sh. If I call this script with the --help switch, I want to display a message to the user.

Is this possible? I only want this message to display if the script is called with the --help switch included.

Please advise.

DaveMac001
  • 155
  • 3
  • 13
  • 1
    Use [`getopt`](https://stackoverflow.com/q/192249/21567). – Christian.K Oct 12 '17 at 09:21
  • You should avoid to use `getopt` as it cannot handle empty arguments strings, or arguments with embedded whitespace. You would use `getopts` instead. Please read Christian's link to get more info about it – Will Oct 12 '17 at 12:51

1 Answers1

0

Here is what I do in all my scripts that needs to handle arguments :

#!/bin/bash
while [[ $# -gt 0 ]]; do
   case $1 in
       -h|--help)
          help
       ;;
       -f|--function)
          myFunction $2
          shift
          shift
       ;;
       *) 
          help
       ;;
   esac
done


myFunction {
echo "My parameter is $1"
}
help {
echo "Help message right here!"
}

Test :

Will:/home/will>./script.sh -h
Help message right here!
Will:/home/will>./script.sh --help
Help message right here!

Will:/home/will>./script.sh -f foobar
My parameter is foobar
Will:/home/will>./script.sh --function foobar
My parameter is foobar

Will:/home/will>./script.sh anythingelse
Help message right here!
Will
  • 1,792
  • 2
  • 23
  • 44