问题
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.
回答1:
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
回答2:
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"
回答3:
don't have to use grep
ifconfig eth0 | awk '/HWaddr/{print $5}'
回答4:
CASS_INTERNAL=`ifconfig eth0 | grep HWaddr | awk '{print \$5}'`
echo $CASS_INTERNAL
Your:
$CASS_INTERNAL
Would try to run it as a command.
回答5:
do you maybe want
echo $CASS_INTERNAL
来源:https://stackoverflow.com/questions/3294909/bash-script-issue