How to update Env variable in Linux?

2019-08-17 05:30发布

I've defined an Env variable : export NBR_PROCESS=2

basically I should be able to update the variable, but when I execute the following script I get the same result on each run:

#!/bin/bash
echo "Script 2: Before decrement : $NBR_PROCESS"
export NBR_PROCESS=$(($NBR_PROCESS - 1))
echo "Script 2: After decrement : $NBR_PROCESS"

on each execution I get the same following result:

Script 2: Before decrement : 2
Script 2: After decrement : 1

What I would like to do is decrement the variable NBR_PROCESS by running the script.

Any idea what I've missed here ? Thank you !

标签: linux bash
3条回答
来,给爷笑一个
2楼-- · 2019-08-17 05:55

You have to "source"

source your_script


EDIT 1
See this answer...


EDIT 2

. filename [arguments] or source filename [arguments]

Complete explanations:

Read and execute commands from the filename argument in the current shell context. If filename does not contain a slash, the PATH variable is used to find filename. When Bash is not in POSIX mode, the current directory is searched if filename is not found in $PATH. 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 exit status of the last command executed, or zero if no commands are executed. If filename is not found, or cannot be read, the return status is non-zero. This builtin is equivalent to source.

查看更多
等我变得足够好
3楼-- · 2019-08-17 06:00

Each time you run your script, it gets a fresh copy of your (or the user it's being executed as) environmental variables - and they stay local to that process. In other words, whatever variables are modified are only modified for that instance.

If the process creates child processes, same thing. The children receive a copy of the parent's environment and any changes they make will "disappear" when they exit.

As Luc M stated, you can use source to have your script(s) execute as Tlc processes. This will allow the contents of said script to also affect your environment.

查看更多
成全新的幸福
4楼-- · 2019-08-17 06:07

A script (or any executable) cannot change an environment variable of the shell, because it is running in a different (child) process. The only way to change the environment inside your shell is thru the export builtin. You could also use the env command to setup the environment of some program, like env YOURVAR=1 yourprogram yourarguments ...

You could use bash functions or the eval or source builtins (to indirectly invoke the export builtin).

Read the advanced bash scripting guide

查看更多
登录 后发表回答