【问题标题】:Set variables in bash script [duplicate]在bash脚本中设置变量[重复]
【发布时间】:2016-02-23 19:30:44
【问题描述】:

test.sh 包含:

A=$1
B=$2

我将 test.sh 设置为 chmod 777

我用 2 个参数启动脚本:

./test.sh first last

然后我通过输入测试它:

echo "FirstVar: $A SecondVar: $B"

结果:

"FirstVar:  SecondVar: "

我做错了什么?

【问题讨论】:

  • 你没有做错什么。您的代码按预期工作(设置变量有效在运行它的解释器范围内)。
  • 无论您想要完成什么,让有权访问系统的每个人都可以写入您的可执行文件是一个严重的安全问题。也许可以尝试chmod 755

标签: linux bash shell command-line echo


【解决方案1】:

当你像这样运行你的脚本时:

./test.sh whatever

Bash 运行另一个 shell 实例,它解释脚本中的命令。如果你想在当前 shell 中设置变量,你应该使用source 命令,或者点(.)。在这种情况下,脚本中的命令将直接在当前 shell 中执行。

source test.sh

或者只是

. test.sh

【讨论】:

    猜你喜欢
    • 2019-01-05
    • 2011-01-28
    • 2018-10-24
    • 2018-10-01
    • 1970-01-01
    • 2021-08-29
    • 2018-08-18
    相关资源
    最近更新 更多