0

So, I have this command I want to execute and then capture the output of:

cat /etc/sysconfig/network-scripts/ifcfgxxx | grep IPADDR | sed -E -e 's/[[:blank:]]+/\n/g'"

However, in my script, the path is a variable:

mypath="/etc/sysconfig/network-scripts/ifcfgxxx"

So my command looks like this:

cat ${mypath} | grep IPADDR | sed -E -e 's/[[:blank:]]+/\n/g'"

When I put this into my script like this, it works:

mypath="/etc/sysconfig/network-scripts/ifcfgxxx"
output="$(cat ${mypath} | grep IPADDR | sed -E -e 's/[[:blank:]]+/\n/g')"
echo ${output}

This is what I get:

IPADDR=192.168.1.3
IPADDR1=192.168.1.4
IPADDR2=192.168.1.5
IPADDR3=192.168.1.6

However, when I put this into my script, it does not work:

mypath="/etc/sysconfig/network-scripts/ifcfgxxx"
mycommand="cat ${mypath} | grep IPADDR | sed -E -e 's/[[:blank:]]+/\n/g'"
output="$(${mycommand})"
echo ${output}

I get a bunch of errors:

cat: |: No such file or directory
cat: grep: No such file or directory
cat: IPADDR: No such file or directory
cat: |: No such file or directory
cat: sed: No such file or directory
cat: 's/[[:blank:]]+/\n/g': No such file or directory

Any idea how I can do this with my command being a variable?

Thanks

Brian
  • 1,726
  • 2
  • 24
  • 62
  • See [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050), which describes this problem in detail. – Charles Duffy Jun 18 '18 at 17:27
  • Don't put commands in variables. It doesn't work, and it makes no sense most of the time. If you need a short name to refer to a long command, write a function. – n. m. could be an AI Jun 18 '18 at 17:28
  • ...if you want to encapsulate code to run it more than once, the right tool is a function. `addressesForPath() { grep IPADDR <"$1" | sed -E -e 's/[[:blank:]]+/\n/g'; }`, later invoked as something like `addressesForPath "$mypath"` – Charles Duffy Jun 18 '18 at 17:30
  • ...note, by the way, that `${foo}` unquoted is just as incorrect as `$foo` unquoted -- both subject the variable's contents to string-splitting and glob expansion, unless quoted as `"$foo"` or `"${foo}"`. See http://shellcheck.net/ for automated detection of this kind of bug. – Charles Duffy Jun 18 '18 at 17:32

0 Answers0