Posted in

Sharing variable between bash scripts

Sharing Variables

The simplest way to share variables between Bash scripts is to place them in a separate common script and source that script wherever the variables are needed.

ShellScript
# common.sh

#!/bin/bash

export SOME_VAR="Hello"

Then, in another script:

ShellScript
# user.sh

#!/bin/bash

source common.sh

echo "SOME_VAR = $SOME_VAR"

Using source executes the contents of common.sh in the current shell, making the exported variables available to the script.

Sharing Arrays

Arrays can be shared in the same way. Define the array in common.sh and source it from another script.

ShellScript
# common.sh

#!/bin/bash

declare -a SOME_ARRAY=("element1" "element2" "element3")

Then use it in another script:

ShellScript
#!/bin/bash

source common.sh

for element in "${SOME_ARRAY[@]}"
do
    echo "$element"
done

Reading Arrays from a File

In many cases, storing the data in a text file is more convenient than hardcoding it inside a script. You can read a single-line list into an array using read:

ShellScript
#!/bin/bash

read -a SOME_ARRAY < data.txt

for element in "${SOME_ARRAY[@]}"
do
    echo "$element"
done

This approach forces you however to store all elements in a single line like:

MDX
element1 element2 element3

For longer lists, where each element is stored on a separate line:

MDX
element1
element2
element3
...

it is better to use mapfile:

ShellScript
#!/bin/bash

mapfile -t SOME_ARRAY < data.txt

for element in "${SOME_ARRAY[@]}"
do
    echo "$element"
done

The -t option removes trailing newline characters, making the array elements cleaner to work with.


Read also: