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.
# common.sh
#!/bin/bash
export SOME_VAR="Hello"
Then, in another script:
# 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.
# common.sh
#!/bin/bash
declare -a SOME_ARRAY=("element1" "element2" "element3")
Then use it in another script:
#!/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:
#!/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:
element1 element2 element3
For longer lists, where each element is stored on a separate line:
element1
element2
element3
...
it is better to use mapfile:
#!/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.
Top comments (0)