Bash script with export variables

Hi all guys,

how you can read in thread title, I'm deploying a bash script in which I have to export some variables inside it.
But (I think you know) the export command works only inside the script and so, on exit command, the variables aren't set like I set inside the script.
Consequently in env file, variables are set like before the run of the script.

So, the question is easy: how can I set permanently the variables inside the script with export command?

Thx, bye.
Fabio

Source the script in the current shell:

. ./script_name

Note the dot `.` shell builtin at the beginning of the line.

Ok, but I need to do a similar thing inside the script.

So do it.

I'm sorry, but you intend for example, if my script is Test.sh e inside the code is:

#!/bin/bash
echo $1 > /tmp/output
bin_dir=$1
export bin_dir
exit 0

you mean I have to do:

#!/bin/bash
echo $1 > /tmp/output
bin_dir=$1
. ./Test.sh
export bin_dir
exit 0

right or not?

No.
if you have a script that sets and/or exports variables that are needed by another script,
you need to source the script that sets the environment inside the script that needs the new environment.

For example:

env_script.sh

export var1=value1 var2=value2 ... 

main_script.sh

# source the env script
. /path/to/env_script.sh
# here the values of var1 and var2 are available

If you need to do something different, please be more specific.

see this post

Another approach if you just want to make the results of a called script available to the parent. Echo the results at the end of the called script and read the results in the parent script:

# abc01 - Top level script
var1="fred"
var2="joe"
var3="nothing"
var4="nothing"
./abc011 "${var1}" "${var2}" | read var3 var4
echo "var3=${var3}"
echo "var4=${var4}"


# abc011 - Script called from abc01
var5="${1}"
var6="${2}"
var7="${var5}-modified"
var8="${var6}-modified"
#
echo "${var7} ${var8}"


./abc01
var3=fred-modified
var4=joe-modified

idro, if I'm understanding the source of your confusion:

Environment variables are not global variables. You can't permanently set them for every other program, from one program. The closest thing there is to setting them globally is /etc/profile, and processes don't automatically get changes when you alter that -- it's read by shells on login and so forth.

How env vars work is child processes get copies from their parent on creation and thereafter are independent -- changes in the parent don't affect the child and vice versa.