简体   繁体   中英

Shell script not running on Mac OS

I have what amounts to a very simple bash script that executes a deployment. Here is my code:

#!/usr/bin/env bash

function print_help
{
  echo '
     Deploy the application.

   Usage:
    -r          reinstall
    -h          show help
    '
}

reinstall=false
while getopts "rh" opt; do
  case ${opt} in
    r)
      echo "clean"
      reinstall=true
      ;;
    h)
      echo "help"
      print_help
      exit 0
      ;;
  esac
done

I am calling the script as follows:

. deploy.sh -h

No matter what I do, neither option (ie -r, -h) results in the respective echo and in the case of -h the print_help function isn't called.

What am doing wrong?

getopts uses a global variable OPTIND to keep track about which argument it processes currently. Each option it parses, it increments/changes OPTIND to keep track which argument will be next.

If you call getopt without changing OPTIND it will start from where it last ended. If it already parsed first argument, it would want to continue parsing from the second argument, etc. Because there is no second argument the second (or later) time you source your script, there is only -h , getopt will just fail, because it thinks it already parsed -h .

If you want to re-parse arguments in current shell, you need to just reset OPTIND=1 . Or start a fresh new shell, which will reset OPTIND to 1 by itself.

If there's a space between the dot and your script name then you're not lauching the script but just sourcing it to your current shell session !

if you want to run your scipt you should do:

# chmod +x ./deploy.sh
# ./deploy.sh -h

if you source it the functtions and variables inside your scipt will be available in your current shell session this could allow you to do things like that:

# . ./deploy.sh
# print_help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM