简体   繁体   中英

Linux shell script to change an environment variable

I'm trying to write a Linux shell script to change an environment variable 'ROS_IP' to my current IP address.

printenv | grep "ROS_IP" 

returns ROS_IP=192.168.1.10

The command

ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'

returns my current ip address 192.168.1.2 which is correct

Here is my shell script

#!/bin/bash

#Command to get current IP address and set the output to a variable 'var'
var=$(ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/')
#Make sure var is the correct IP
echo $var
#Set ROS_IP
export ROS_IP=$var
#end script

after the script has run, running the command

printenv | grep "ROS_IP" 

still returns the old output ROS_IP=192.168.1.10

How can I fix this issue?

What you want won't work if you execute the script via:

bash script.sh  # won't work

Or:

./script.sh  # won't work even if script has executable bit set

Instead, you must source it:

. script.sh

Or, if you prefer:

source script.sh

The issue is that subshells cannot alter the environment of the parent shell. The export command applies to the shell running the script and its subshells but not its parent shell. Thus, the commands must be run in the parent shell. This is what sourcing does.

Documentation

Sourcing is documented in man bash :

filename [arguments]
source filename [arguments]
Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename. If filename does not contain a slash, filenames in PATH are used to find the directory containing filename. The file searched for in PATH need not be executable. When bash is not in posix mode, the current directory is searched if no file is found in PATH. If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read. [emphasis added]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM