2

I have adapted some code I had to handle just a single possible option. Either run the function or use the help option to give a brief description.

activate-jet ()
{
 local  iarg=0  narg="$#"
 while (( narg > 0 )); do
   opt="$1" ; iarg=$(( iarg + 1 ))
   case $opt in
     ("-h"|"--help")  echo "TODO" ; return ;;
     (*)  break ;;
   esac
 done
}

I would like to simplify it more if I can, without introducing any strange behaviour by the user when called.

1 Answer 1

1

This is a possibility, since you state that you only need one argument, therefore there's no need for looping or "casing":

$ activate_jet() { 
    [[ "$#" -gt 1 ]] && echo "Invalid number of arguments" && return
    if [[ ! -z "$1" ]]; then 
      if [[ "$1" = "-h" || "$1" = "--help" ]]; then
        echo "TODO" && return
      else
        echo "Bad argument" && return
      fi
    fi 
    echo "jet activated"
  }
$ activate_jet foo bar
Invalid number of arguments
$ activate_jet foo
Bad argument
$ activate_jet -h
TODO
$ activate_jet --help
TODO
$ activate_jet
jet activated

Now note that I changed the name of the function replacing the hyphen for an underscore: activate_jet instead of activate-jet, because the hyphen may not be compatible with some shells:

Conclusions

  • Hyphens are non-standard. Stay away from them if you want cross-shell compatibility.
  • Use underscores instead of hyphens: underscores are accepted everywhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.