将输出分配给 Bash 中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8737638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:26:27  来源:igfitidea点击:

Assign output to variable in Bash

bashcurl

提问by Alex Bliskovsky

I'm trying to assign the output of cURL into a variable like so:

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

#!/bin/sh
$IP=`curl automation.whatismyip.com/n09230945.asp`
echo $IP
sed s/IP/$IP/ nsupdate.txt | nsupdate

However, when I run the script the following happens:

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

./update.sh: 3: =[my ip address]: not found
./update.sh: 3: =[my ip address]: not found

How can I get the output into $IPcorrectly?

我怎样才能$IP正确地得到输出?

回答by ghoti

In shell, you don't put a $ in front of a variable you're assigning. You only use $IP when you're referring to the variable.

在 shell 中,您不会在要分配的变量前放置 $。只有在引用变量时才使用 $IP。

#!/bin/bash

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

echo "$IP"

sed "s/IP/$IP/" nsupdate.txt | nsupdate

回答by Kostas Demiris

Same with something more complex...getting the ec2 instance region from within the instance.

与更复杂的事情相同……从实例中获取 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