当前位置: 动力学知识库 > 问答 > 编程问答 >

bash - reassigning Global variables in shell scripts

问题描述:

I am new to shell scripting and I need some help on the following problem:

I have script. It has a global variable defined as follows:

ARCHIVE_USER=user1

Then, in a method, I am changing the values for these variables:

test_function(){

ARCHIVE_USER=user2

test_function2()

}

test_function2(){

echo ARCHIVE_USER

}

I want test_function2 to print "user2" instead of "user1" because in the test_function I have renamed the variable value to "user2", but when I run it, it is always giving me "user1" as the output. What am I doing wrong here?

网友答案:

This script works as you expect it should, i.e. it prints "B".

#!/usr/bin/bash

TEST=A

test_a()
{ 
    TEST=B
    test_b
}

test_b()
{
    echo $TEST
}

test_a

So, my question to you is how are you calling your test_function()?

网友答案:

You should define those function in the same environment.

If you put them in different scripts, and run them by /path/to/script_1.sh and /path/to/script_2. They will not affect each other. Because they run in different environment.

You should read more about subshell/subprocess.

分享给朋友:
您可能感兴趣的文章:
随机阅读: