Sometimes, programming in shell scripting needs input ip address from stdin or variables. By default, ip address can be acquired by ifconfig command. This simple tutorial will show you howto cut output string from shell to get piece of string that you need. Login with root or sudo from your user account then run this ifconfig command.
root@war49:/home/war49# ifconfig eth0
eth0 Link encap:Ethernet HWaddr a4:ba:db:d8:05:97
inet addr:192.168.1.2 Bcast:192.168.1.255 Mask:255.255.255.0
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
Interrupt:47
We just need ip string (192.168.1.2), and we didn't need anything else. So, what should we do to obtain it string?. Linux has many string manipulation tools like sed, grep, fgrep, awk, cut and more. When we wanna print just line 2 of ifconfig output command, we use pipeline "|" to join more than one command. Then, filter the output with grep or fgrep command.
root@war49:/home/war49# ifconfig eth0 | grep 'inet addr'
inet addr:192.168.1.2 Bcast:192.168.1.255 Mask:255.255.255.0
*note: Pipeline is a character | (pipe) that read output from command 1 then push it output as input for command 2.
*use: command 1 | command 2
From the second line output of ifconfig command, we get 3 information: inet address (ip), broadcast address, and Netmask. We just wanna print ip address not broadcast address, nor netmask. So, we can split it with awk and cut command, as appeared below.
# awk .. is a scripting language, in this section awk is needed to select and print second string and leave other string.
root@war49:/home/war49# ifconfig eth0 | grep 'inet addr' | awk '{print $2}'
addr:192.168.1.2
# cut .. is a command to split a string divided by specified character
root@war49:/home/war49# ifconfig eth0 | grep 'inet addr' | awk '{print $2}' | cut -d: -f 2
192.168.1.2
'Cut' command has -d and -f option, -d specifying a delimiter, -f number of field or which field would we choosen in the string. It could be nice store shell output to environment variable and put it at variables declaration.
root@war49:/home/war49# MY_IP=`ifconfig eth0 | grep 'inet addr' | awk '{print $2}' | cut -d: -f 2`
root@war49:/home/war49# echo $MY_IP
192.168.1.2
root@war49:/home/war49# echo "My ip address is: $MY_IP"
My ip address is: 192.168.1.2
Howto Split a String in shell scripting and Get IP Address string from Shell
Feb 10, 2012 6:20 AM
Filed Under: linux, shprog |0 comments
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment