增加环境变量

3 linux bash shell sh

我需要通过以下步骤增加环境变量:

envar=1
export envar
sh script_incrementation
echo $envar
Run Code Online (Sandbox Code Playgroud)

其中 script_incrementation 包含如下内容:

#! /bin/sh
envar=$[envar+1] #I've tried also other methods of incrementation
export envar
Run Code Online (Sandbox Code Playgroud)

无论我做什么,在退出脚本后,变量仍保持其初始值 1。

谢谢你的时间。

mer*_*011 12

shell 脚本在它自己的 shell 中执行,因此除非您提供它,否则您无法影响外壳程序。有关该讨论的详细信息,请参阅此问题

考虑以下脚本,我将其称为Foo.sh.

#!/bin/bash

export HELLO=$(($HELLO+1))
Run Code Online (Sandbox Code Playgroud)

假设在外壳中,我定义了一个环境变量:

export HELLO=1
Run Code Online (Sandbox Code Playgroud)

如果我像这样运行脚本,它会在自己的 shell 中运行,并且不会影响父级。

./Foo.sh
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用它,它只会执行当前shell 中的命令,并且会达到预期的效果。

. Foo.sh
echo $HELLO # prints 2
Run Code Online (Sandbox Code Playgroud)