3

I can run this command fine, with the output I want:

ifconfig eth0 | grep HWaddr | awk '{print $5}'

However, when I set the command to a variable, and print the variable, I get an error:

CASS_INTERNAL=`ifconfig eth0 | grep HWaddr | awk '{print \$5}'`
$CASS_INTERNAL

my internal xxx ip: command not found

The weird thing - my internal IP actually shows up. How do I go about this without getting an error? It shouldn't matter, but I'm using the latest version of Ubuntu.

  • Using back quotes (i.e. `) surrounding the command actually executes it. So you are executing the command on the first line and storing the result in CASS_INTERNAL. As Wikken says, you then simply want to return the result using "echo". An alternative would be to store the command text in CASS_INTERNAL (using double quotes - not backquotes) and executing it using simply $CASS_INTERNAL. In your example, you are executing it using backquotes on the first line and again on the second line using $CASS_INTERNAL. – xagyg Jul 20 '10 at 23:02

5 Answers5

4

You're not printing the variable, you're running it as a command name. You're looking for

echo "$CASS_INTERNAL"

(Get into the habit of always putting double quotes around variable substitutions.)

More advanced shell note: in this case it doesn't matter, but in general echo can have trouble with some special characters (- and \\), so it's better to use the following more complicated but fully reliable command:

printf "%s\n" "$CASS_INTERNAL"
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
4

don't have to use grep

ifconfig eth0 | awk '/HWaddr/{print $5}'
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
3
CASS_INTERNAL=`ifconfig eth0 | grep HWaddr | awk '{print \$5}'`
echo $CASS_INTERNAL

Your:

$CASS_INTERNAL

Would try to run it as a command.

Wrikken
  • 69,272
  • 8
  • 97
  • 136
1

do you maybe want

echo $CASS_INTERNAL
second
  • 28,029
  • 7
  • 75
  • 76
0

Well, you grep for HWaddr first, so the fifth field on this this line is the MAC address of the network adapter in question - not your local IP address.

Others have suggested the solution is to simply echo the result, meaning if eth0 in this example is not available at that point in time which the line gets executed, it will not work.

From what I understand you wish instead to put the desired command line in a variable, then evaluate it later on. This pattern is commonly called lazy evaluation, and is made possible in bash by using the eval builtin:

#put the desired command in variable
CASS_INTERNAL='ifconfig eth0 | grep HWaddr | awk "{print \$5}"'

# ....

#at later on - evaluate its contents!
eval $CASS_INTERNAL
11:22:33:aa:bb:cc
Community
  • 1
  • 1
conny
  • 9,973
  • 6
  • 38
  • 47