0

I am trying to parse the IP address from ifconfig command. It works fine when I do it on the command line

pb791b@pb791b-VirtualBox:~/devtest/ngs/base/Tests/shellScripts$ ifconfig enp0s3 | sed -n '/inet addr/s/.*addr.\([^ ]*\) .*/\1/p'
192.168.1.112

But it gives error when I use it in a expect script.

#!/usr/bin/expect 

set pidBash [ spawn bash ]

set ipIfConfig {ifconfig enp0s3 | sed -n '/inet addr/s/.*addr.\([^ ]*\) .*/\1/p'}
set clientIP [exec "echo $ipIfConfig"]
puts "clientIP = $clientIP" 
exit 1

The output is

pb791b@pb791b-VirtualBox:~/devtest/ngs/base/Tests/shellScripts$ ./ifconfig_parse.sh 
spawn bash
couldn't execute "echo ifconfig enp0s3 | sed -n '/inet addr/s/.*addr.\([^ ]*\) .*/\1/p'": no such file or directory
    while executing
"exec "echo $ipIfConfig""
    invoked from within
"set clientIP [exec "echo $ipIfConfig"]"
    (file "./ifconfig_parse.sh" line 7)

2 Answers2

1

Try like this:

set ip [exec ifconfig enp0s3 | sed -n {/inet addr/s/.*addr.\([^ ]*\) .*/\1/p}]
puts ip=$ip

See Command substitution and exec in Tcl's manual.

pynexj
  • 19,215
  • 5
  • 38
  • 56
  • You should explain why, single quotes vs braces. – glenn jackman Sep 09 '17 at 18:46
  • @whjm Thanks. Have to be careful when to use quotes vs. braces. I was able to also extract the IP address without using 'sed' using this if {[regexp {inet addr:(\S+)} [exec ifconfig enp0s3] -> clientIP]} { puts "clientIP = $clientIP" } – Piyush Bhagat Sep 14 '17 at 17:57
0

Here a concise and simple awk script to extract ip

For ip4:

ifconfig eno1 |awk '/inet /{print $2}'

For ip6

ifconfig eno1 |awk '/inet6/{print $2}'

For both ip4 and ip6

ifconfig eno1 |awk '/inet/{print $2}'

Essentially the script should be:

set ip [ ifconfig eno1 |awk '/inet /{print $2}' ] 
Dudi Boy
  • 4,551
  • 1
  • 15
  • 30