DEV Community

Cover image for Sharing variable between bash scripts
piko::tutorial
piko::tutorial

Posted on • Originally published at pikotutorial.com

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.

# common.sh

#!/bin/bash

export SOME_VAR="Hello"
Enter fullscreen mode Exit fullscreen mode

Then, in another script:

# user.sh

#!/bin/bash

source common.sh

echo "SOME_VAR = $SOME_VAR"
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

Then use it in another script:

#!/bin/bash

source common.sh

for element in "${SOME_ARRAY[@]}"
do
    echo "$element"
done
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

element1 element2 element3
Enter fullscreen mode Exit fullscreen mode

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

element1
element2
element3
...
Enter fullscreen mode Exit fullscreen mode

it is better to use mapfile:

#!/bin/bash

mapfile -t SOME_ARRAY < data.txt

for element in "${SOME_ARRAY[@]}"
do
    echo "$element"
done
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)