Score:0

Using redirection to write a command using a file

jp flag

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 192.168.1.203 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?

Score:0
my flag

Try this:

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

Explanations:

  • 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
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.