234

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

#!/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 

How can I get the output into $IP correctly?

3
  • The accepted answer is correct, but there's another minor distinction between that example and what's here: if the $IP var passed to echo is not wrapped in double quotes, it will only output the last line of the captured curl output. Commented Dec 5, 2018 at 20:57
  • Thanks @ChristopherHunter, I came here just looking for this. Why does it behave this way though? Commented May 23, 2020 at 8:46
  • 1
    @Amey I can't say exactly what the reasoning was, just that this is how echo behaves when you give it a multi-line string as an argument. Commented Jun 18, 2020 at 0:11

2 Answers 2

404

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.

#!/bin/bash IP=$(curl automation.whatismyip.com/n09230945.asp) echo "$IP" sed "s/IP/$IP/" nsupdate.txt | nsupdate 
Sign up to request clarification or add additional context in comments.

8 Comments

Is there a way to suppress the output and progress bar of curl? Adding -silent leaves $IP empty...
@Dror, curl sends its noisy output to stderr, so the progress bar should be ignored in the case of a script like this. Nevertheless, --silent or -s works just fine. If you have troubles, please ask a question.
Use curl -s to disable the progress bar and error messages.
You can always redirect stderr: IP=$(curl <url> 2>/dev/null)
finding with the $() syntax i'm not able to use env variables e.g. instead of hard coding an email I want to use $2, $3 as variables. Any ideas on why these wont render?
|
42

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

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 

4 Comments

This was exactly what I was doing in my bash script and you saved me from having to apt-get install jq!
How can this be done on windows? if I substitute the $ with os.system, INSTANCE_REGION does not have the value of the output.
How to make that multi-line?
@KhalilGharbaoui just use \ in the end of the line

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.