在Bash中将输出分配给变量

Ale*_*sky 148 bash curl

我正在尝试将cURL的输出分配给变量,如下所示:

#!/bin/sh
$IP=`curl automation.whatismyip.com/n09230945.asp`
echo $IP
sed s/IP/$IP/ nsupdate.txt | nsupdate
Run Code Online (Sandbox Code Playgroud)

但是,当我运行脚本时,会发生以下情况:

./update.sh: 3: =[my ip address]: not found
Run Code Online (Sandbox Code Playgroud)

如何才能$IP正确输出?

gho*_*oti 262

在shell中,你不要在你分配的变量前放一个$.您在引用变量时只使用$ IP.

#!/bin/bash

IP=$(curl automation.whatismyip.com/n09230945.asp)

echo "$IP"

sed "s/IP/$IP/" nsupdate.txt | nsupdate
Run Code Online (Sandbox Code Playgroud)

  • @Dror,`curl`将其嘈杂的输出发送到stderr,因此在这样的脚本的情况下应该忽略进度条.不过,`--silent`或`-s`的工作正常.如果您遇到麻烦,请[问一个问题](http://stackoverflow.com/questions/ask). (4认同)
  • 有没有办法抑制`curl`的输出和进度条?添加`-silent`会将`$ IP`留空...... (2认同)

Kos*_*ris 25

与更复杂的东西相同......从实例中获取ec2实例区域.

INSTANCE_REGION=$(curl -s 'http://169.254.169.254/latest/dynamic/instance-identity/document' | python -c "import sys, json; print json.load(sys.stdin)['region']")

echo $INSTANCE_REGION
Run Code Online (Sandbox Code Playgroud)