【问题标题】:Passing variables to bash script vs setting env variables for the script [closed]将变量传递给bash脚本与为脚本设置环境变量[关闭]
【发布时间】:2017-05-24 08:59:33
【问题描述】:

将一些环境变量传递给脚本的最佳方法是什么?

./script.sh ${A} ${B}

A=${A} B={$B} ./script.sh

我一直看到第一种,但我的一位同事说第二种方法更好,因为当您添加不需要的新参数时,您不必记住变量的顺序和脚本内部从$* 解析它。

除了让脚本调用时间长一点外,后者有什么禁忌吗?

我不想使用export(因为每个脚本都可以访问环境变量),也不想在调用脚本之前使用.(我想让脚本只使用变量的一个子集)

【问题讨论】:

    标签: bash parameter-passing


    【解决方案1】:

    当您的参数数量有限时,可以使用位置参数。

    如果您有一个包含多个参数的复杂脚本,命名参数是首选方式。

    命名参数有几种方法:

    1. 你提到的方法:

      A=${A} B={$B} ./script.sh

    2. 使用 getopt

    goodcoding getoptposix getopt man

    1. 使用 getopts

    getopts_tutorialposix getopts man

    【讨论】:

      猜你喜欢
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      • 1970-01-01
      • 2011-03-05
      相关资源
      最近更新 更多