在shell脚本内部设置变量,以便在外部用于下一个命令

在shell脚本内部设置变量,以便在外部用于下一个命令,shell,Shell,我试图在Shell脚本中使用Shell变量,我的Shell脚本如下 HerculesResponse=$(curl-X POST-H“内容类型:应用程序/json”-H“缓存控制:无缓存”-d'{“testID”:“591dc3cc4d5c8100054cc30b”,“testName”:“stagetest”,“poolID”:“5818baa1e4b0c84637ce36b4”,“poolName”:“Default”,“dashboardID”:“582e3a2f5f5c50000124c

我试图在Shell脚本中使用Shell变量,我的Shell脚本如下

HerculesResponse=$(curl-X POST-H“内容类型:应用程序/json”-H“缓存控制:无缓存”-d'{“testID”:“591dc3cc4d5c8100054cc30b”,“testName”:“stagetest”,“poolID”:“5818baa1e4b0c84637ce36b4”,“poolName”:“Default”,“dashboardID”:“582e3a2f5f5c50000124c18a”,“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“=”-f2)
echo$runId

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

testStatus=$(curl-xgethttps://example.com:8080/runs/$runId)


我尝试使用export runId命令,但在运行shell脚本时不起作用

,它设置的变量在执行完成后将丢失,调用shell将无法使用这些变量。提取变量值的正确方法是:

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

    run_id=$(/path/to/script.sh)
    
    . /path/to/script.sh
    
这种方法的缺点是脚本的所有输出都将在变量中结束。在您的例子中,
echo$reportURL
以及
echo$runId
的输出

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

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


另见:


export
使变量可用于子进程,即您稍后启动的进程。它不使它们可用于父进程(即启动您的进程)。