-2

I'm trying to run a command that grabs my current IP address (or addresses) and saves this to a variable so that I can then see on screen. I want to do this so that I can run this in a script and use the variable in a loop.

userip='ifconfig | grep "inet addr:" | cut -d: -f2  |  awk '{print $1}''

echo $userip

Everytime I run this command, its basically getting the speech marks mixed up and thus not running whole command.

It's really just got 'ifconfig | grep "inet addr:" | cut -d: -f2 | awk ' in the single quotations.

Any advice would be extremely helpful thanks.

  • 1
    You cannot embed single-quotes within a single-quoted string (`'{print $1}'`). In fact, the syntax highlighting of your own question could serve as a clue. – John Bollinger Sep 15 '15 at 18:54
  • 1
    **thus not running whole command** Doing `echo` won't run the `ifconfig` command. What are you trying to do here? – anubhava Sep 15 '15 at 18:57
  • I've tried mixing up the double and single quotations. My echo command is just to output the result, hoping my IP address will appear. – robot420 Sep 15 '15 at 19:01
  • @robot420 Did you mean to assign *the result* of the command to `userip`? In that case `$()` is what you want, not single quotes. – Biffen Sep 15 '15 at 19:02
  • Yes $() worked. Thanks a lot. @Biffen Yeah when i ran the command without assigning it to the variable, it did give me 2 addresses. This should be simple to fix :) – robot420 Sep 15 '15 at 19:12
  • 1
    @robot420 This is an excellent example of how you could have gotten the right answer much quicker (or even found it yourself) if you had *properly described the problem from the start*! – Biffen Sep 15 '15 at 19:15
  • @Biffen honestly i sat here for about 10 minutes changing the title to what I thought was good. What would you have said? – robot420 Sep 15 '15 at 19:18
  • @robot420 Well, a clear description of the problem, including expected output and actual output are common ingredients of a good question. Have you read [this](http://stackoverflow.com/help/how-to-ask)? – Biffen Sep 15 '15 at 21:24
  • :Voted to reopen as the duplicate doesn't answer the needs of the original question. – KevinDTimm Sep 16 '15 at 13:53

2 Answers2

0

The problem you have is that the single quotes you have are incorrect, they should be grave accent so, not ' but instead `

KevinDTimm
  • 14,226
  • 3
  • 42
  • 60
0

Check that your command string to isolate the IP address is contained in back quotes. The back quote ` is different than the single quote ' or double quote " (assuming the command line works for your OS). Thus:

userip=`ifconfig | grep "inet addr:" | cut -d: -f2  |  awk '{print $1}'`

The back quotes cause the command to be executed and the results returned. The backquote is below the tilda ~ on most keyboards. (not sure the back quote is appearing in my answer. Just getting used to Stack Exchange.)

Biffen
  • 6,249
  • 6
  • 28
  • 36
John Argo
  • 36
  • 3