This is kind of expected since export
sets the environment variable for that particular shell.
Docs -
export command is used to export a variable or function to the
environment of all the child processes running in the current shell.
export -f functionname # exports a function in the current shell. It
exports a variable or function with a value.
So when you create a sh
script it runs the specified commands into a different shell which terminates once the script exits.
It works with the sh
script too -
data.sh
#!/bin/bash
IFS=$'\t'; while read -r k v; do
export "$k=\"$v\""
echo $HELLO1
echo $SAMPLEKEY
done < <(jq -r '.data | to_entries[] | [(.key|ascii_upcase), .value] | @tsv' data.json)
Output -
$ ./data.sh
"world1"
"world1"
"samplevalue"
Which suggests that your variables are getting exported but for that particular shell env.
In case you want to make them persistent, try putting scripts or exporting them via ~/.bashrc
OR ~/.profile
.
Once you put them in ~/.bashrc
OR ~/.profile
, you will find the output something as below -
I used ~/.bash_profile
on my MAC OS -
Last login: Thu Jan 25 15:15:42 on ttys006
"world1"
"world1"
"samplevalue"
viveky4d4v@020:~$ echo $SAMPLEKEY
"samplevalue"
viveky4d4v@020:~$ echo $HELLO1
"world1"
viveky4d4v@020:~$
Which clarifies that your env variables will get exported whenever you open a new shell, the logic for this lies in .bashrc
(https://unix.stackexchange.com/questions/129143/what-is-the-purpose-of-bashrc-and-how-does-it-work)
Put your script as it is ~/.bashrc
at the end -
IFS=$'\t'; while read -r k v; do
export "$k=\"$v\""
echo $HELLO1
echo $SAMPLEKEY
done < <(jq -r '.data | to_entries[] | [(.key|ascii_upcase), .value] | @tsv' data.json)
You need to make sure that data.json
stays in user's home directory.