Reputation: 1989
I am trying to execute, what I thought would be, a simple shell command within a script. When I execute this from the command prompt, it works well:
$ sudo cat /etc/sysconfig/network-scripts/ifcfg-en0 | grep "IPADDR"
IPADDR=192.168.1.10
However, if I put this into a shell script:
#!/usr/bin/sh
my_command=`sudo cat /etc/sysconfig/network-scripts/ifcfg-en0 | grep "IPADDR"`
${my_command}
echo $?
I get this error:
$ sudo ./myscript.sh
./myscript.sh: line 3: IPADDR=192.168.1.10: command not found
So, how can I successfully execute this line within my shell script?
Thanks!
Upvotes: 0
Views: 219
Reputation: 12036
The problem in your case is that you are executing the result of the command...
This line executes the code as it's between "``" that are special characters for executing the given string as a command:
my_command=`sudo cat /etc/sysconfig/network-scripts/ifcfg-en0 | grep "IPADDR"`
as a result, $my_command
is "IPADDR=192.168.1.10
"
Then you are trying to execute it for the second time:
${my_command}
Thats why you are getting this error. There is no such a command as "IPADDR=192.168.1.10
".
Just use $my_command
as a result that contains your desired grepped part and skip the ${my_command}
line:
#!/usr/bin/sh
my_command=`sudo cat /etc/sysconfig/network-scripts/ifcfg-en0 | grep "IPADDR"`
echo $my_command
Upvotes: 1