【问题标题】:Set variable inside a shell script to be used outside for the next command在 shell 脚本中设置变量以在外部用于下一个命令
【发布时间】:2023-03-18 11:42:01
【问题描述】:

我正在尝试在 shell 脚本中使用 shell 变量,我的 shell 脚本如下

HerculesResponse=$(curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{ "testID": "591dc3cc4d5c8100054cc30b", "testName": "stagetest", "poolID": "5818baa1e4b0c84637ce36b4", "poolName": "Default", "dashboardID": "582e3a2ff5c650000124c18a", "dashboardName": "Default", "dateCreated": "2017-05-23T13:51:23.558Z", "callbackHeader": {}, "active": true }' "https://example.com:8080/run") reportURL=$(expr "$HerculesResponse" : '.*"reportURL":"\([^"]*\)"') echo $reportURL runId=$(echo $reportURL | cut -d"=" -f 2) echo $runId

如何在这个 shell 脚本之外使用 runId 变量来运行命令

testStatus=$(curl -X GET https://example.com:8080/runs/$runId)

我尝试使用 export runId 命令但不起作用

【问题讨论】:

  • export 使变量可用于 进程 - 即您稍后启动的进程。它不会使它们可用于 进程(即启动您的进程)。

标签: shell


【解决方案1】:

当您运行您的 shell 脚本时,它设置的变量会在执行完成后丢失,并且它们将无法用于调用 shell。提取变量值的正确方法是:

  • 让脚本输出变量的值并使用命令替换将该值分配给调用 shell 中的变量,如下所示:

    run_id=$(/path/to/script.sh)
    

这种方法的缺点是脚本的所有输出都会出现在变量中。在您的情况下,echo $reportURLecho $runId 的输出。

  • 使用.source 命令在当前shell 中运行脚本,如下所示:

    . /path/to/script.sh
    

    source /path/to/script.sh
    

另见:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 2018-01-01
    • 2021-10-11
    相关资源
    最近更新 更多