0

I have a shell script that assigns my IP address to a variable, but after running the script, I cannot access the variable in bash. If I put an echo in the script, it will print the variable, but it does not save it after the script is done running.

Is there a way to change the script to access it after it runs?

ip=$(/sbin/ifconfig | grep "inet " | awk '{print $2}' | grep -v 127 | cut -d":" -f2)

I am using terminal on a Mac.

Jeremy
  • 59
  • 6

1 Answers1

3

A script by default runs in a a child process, which means the current (calling) shell cannot see its variables.

You have the following options:

  • Make the script output the information (to stdout), so that the calling shell can capture it and assign it to a variable of its own. This is probably the cleanest solution.

    ip=$(my-script)
    
  • Source the script to make it run in the current shell as opposed to a child process. Note, however, that all modifications to the shell environment you make in your script then affect the current shell.

    . my-script # any variables defined (without `local`) are now visible
    
  • Refactor your script into a function that you define in the current shell (e.g., by placing it in ~/.bashrc); again, all modifications made by the function will be visible to the current shell:

    # Define the function
    my-func() { ip=$(/sbin/ifconfig | grep "inet " | awk '{print $2}' | grep -v 127 | cut -d":" -f2); }
    
    # Call it; $ip is implicitly defined when you do.
    my-func
    

As an aside: You can simplify your command as follows:

/sbin/ifconfig | awk '/inet / && $2 !~ /^127/ { print $2 }'
mklement0
  • 382,024
  • 64
  • 607
  • 775