I´m starting to use Ubuntu as my secondary OS and I´m creating a script which writes the current IP configuration in a file using redirection (with the command $sudo ifconfig -a > /etc/scripts/current-ipaddress) and the next thing I want to do is using one of the values written in that external file for the next command, if possible.

For example, lets say I run $sudo ifconfig -a > /etc/scripts/current-ipaddress and the IP address for eth0 is and the next thing I want to do is making this IP the static one using the command $sudo ifconfig eth0 x.x.x.x. The idea is substituting this x.x.x.x with the real IP (which will be extracted from the file it was written using redirections previously). How can I make this work?

1 Answer 1


Try this:

theip=$(cat /etc/scripts/current-ipaddress | awk '/^eth0:/{flag = 1; next} flag == 1 && / inet / {print $2} /^[^ ]/ {flag=0}')


  • cat filename: print the file content
  • awk: work on text input flow from pipe (the file content)
    • /^eth0:/{flag = 1; next}: search for line who start with eth0: token and put value 1 in variable flag then treat the next line.
    • flag == 1 && / inet / {print $2}: if variable flag equal to 1 and line contains inet token, then print the second field (by default the field separators and spaces)
    • /^[^ ]/ {flag=0}: if line do not starts by a space, put 0 value in the flag variable
  • theip=$(...command...): put the command standard output in the variable theip

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.