简体   繁体   English

Shell 脚本未在 Mac OS 上运行

[英]Shell script not running on Mac OS

I have what amounts to a very simple bash script that executes a deployment.我有一个非常简单的 bash 脚本来执行部署。 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.无论我做什么,这两个选项(即-r,-h)都不会导致相应的echo ,并且在-h的情况下,不会调用print_help function。

What am doing wrong?做错了什么?

getopts uses a global variable OPTIND to keep track about which argument it processes currently. getopts使用全局变量OPTIND来跟踪它当前处理的参数。 Each option it parses, it increments/changes OPTIND to keep track which argument will be next.它解析的每个选项,它递增/更改OPTIND以跟踪哪个参数将是下一个。

If you call getopt without changing OPTIND it will start from where it last ended.如果您在不更改OPTIND的情况下调用getopt ,它将从上次结束的位置开始。 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 .如果它已经解析了第一个参数,它会希望从第二个参数继续解析,等等。因为在第二次(或以后)你获取脚本时没有第二个参数,所以只有-hgetopt将失败,因为它认为它已经解析了-h

If you want to re-parse arguments in current shell, you need to just reset OPTIND=1 .如果要重新解析当前 shell 中的 arguments,只需重置 OPTIND OPTIND=1即可。 Or start a fresh new shell, which will reset OPTIND to 1 by itself.或者启动一个全新的 shell,它会自行将OPTIND重置为1

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 !如果点和脚本名称之间有空格,那么您不会启动脚本,而只是将其采购到您当前的 shell session !

if you want to run your scipt you should do:如果你想运行你的 scipt 你应该这样做:

# 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:如果您获取它,您的 scipt 中的函数和变量将在您当前的 shell session 中可用,这可以让您执行以下操作:

# . ./deploy.sh
# print_help

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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