[shell] Shell script to set environment variables

I wish to write a shell script to export variables.

Below I have listed the script .

echo "Perform Operation in su mode"
export ARCH=arm
echo "Export ARCH=arm Executed"
export PATH='/home/linux/Practise/linux-devkit/bin/:$PATH';
echo "Export path done"
export CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-';
echo "Export CROSS_COMPILE done"

But this doesn't seem to work properly. I have to individually execute the commands at the shell prompt instead.

This question is related to shell

The answer is


You need to run the script as source or the shorthand .

source ./myscript.sh

or

. ./myscript.sh

This will run within the existing shell, ensuring any variables created or modified by the script will be available after the script completes.

Running the script just using the filename will execute the script in a separate subshell.


Run the script as source= to run in debug mode as well.

source= ./myscript.sh

I cannot solve it with source ./myscript.sh. It says the source not found error.
Failed also when using . ./myscript.sh. It gives can't open myscript.sh.

So my option is put it in a text file to be called in the next script.

#!/bin/sh
echo "Perform Operation in su mode"
echo "ARCH=arm" >> environment.txt
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export "CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?" >> environment.txt
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...

Tnen call it whenever is needed:

while read -r line; do
    line=$(sed -e 's/[[:space:]]*$//' <<<${line})
    var=`echo $line | cut -d '=' -f1`; test=$(echo $var)
    if [ -z "$(test)" ];then eval export "$line";fi
done <environment.txt