Skip to content

Instantly share code, notes, and snippets.

@mkelley33
Created June 15, 2012 02:28
Show Gist options
  • Save mkelley33/2934381 to your computer and use it in GitHub Desktop.
Save mkelley33/2934381 to your computer and use it in GitHub Desktop.
Copy computer's IP address to clipboard
# When testing a rails website on my local development machine, I found my
# Parallel's VM wouldn't load 0.0.0.0:3000, 127.0.0.1, or localhost:3000.
#
# So I tried using my computers IP address and voila. I thought I'd hone
# my bash chops a little and extract the IP address with the port number
# concatenated to it. This command puts that on the clipboard so I can just
# paste it into IE so I could browser test.
#
# NOTE: the pbcopy command is Mac specific.
#
# In my .profile:
alias cpip="ifconfig \
| grep en1 -A1 \
| grep -Eo 'inet\ [1-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' \
| cut -c 6- \
| xargs -I {} echo {}:'3000' \
| pbcopy"
@RichardBronosky
Copy link

You should get in the habit of writing bash functions instead of aliases. Functions don't need the double quotes, can span multiple lines, and can use arguments or stdin. But, good work here. I like seeing Mac users getting Nerdy.

Also, any time you find yourself changing multiple grep commands, it's a good opportunity to use sed or awk. In this case, because of the -A1, awk would be best. Flow control is a mess in sed.

oneliner

cpip(){ ifconfig | awk '/^en1:/ {x=1} x==1 && /inet / {print $2":3000";exit}'; }

readable

cpip(){
  # notice that you can use a pipe at the end of a line rather than a backslash
  ifconfig |
  awk '
    ## awk evaluates the entire script for every line in the input ##

    # when you find the proper interface, set the variable x as a flag
    /^en1:/ {x=1}
    # if the flag is set and you find "inet " (not "inet6")...
    x==1 && /inet / {
      # print the 2nd string from the line concatenated with ":3000" 
      print $2":3000"
      # explicitly quit evaluating in case there are additional inet lines
      exit
    }
    # otherwise continue to the next line
  '
}

@mkelley33
Copy link
Author

Thanks for the tips, code, and explanation. Learning more about bash scripting is at the top of my list so this is much appreciated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment