2

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?

1
  • 1
    echo $ARCHIVE_USER should be better in your test_function2(). Or you can use "export" to set the to the entire environment. Example : export ARCHIVE_USER=user1. Commented May 10, 2012 at 8:13

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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()?

1 Comment

Yes, you are correct, i have given a sample script here, in my original script, before asigning value B to TEST variable, test_b is called by some other function. that has making the problem. your answer helped me to nail down the issue. thanks for your time...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.