Dynamically setting of environment variable... Can it be done?

Hi all,
I am fairly new to unix scripting and will like to know how to dynamically set the name of an environment variable to be used.

We have a .env file where we defined the names and locations of data files, trigger files, directories .... etc

Example of variables defined in .env
data_file_123=sales.dat
data_file_456=expenses.dat
data_file_789=profits.dat

I need to create a script (.ksh) that is flexible enough to load different data files depending on the parameter received. Also, based on this parameter I will need to verify if the files exist and this is where I will need to utilized the variables defined in the .env file.
The load script will received the parameter �123� or �456� or �789� (param1)

A couple of scenarios I tried that didn't work are:
if [[ ! -f $data_file_$param1 ]]; then .....

if [[ ! -f ${data_file_$param1} ]]; then .....

I hope I explained my issue adequately and that I've given enough information.
Thank you!

If you have a new enough ksh, you can do things like this:

$ NAME="VAR"
$ VAR="1234"
echo "${!NAME}"
1234
$

If you don't, it's going to be ugly:

$ data_file_123=sales.dat
$ PARAM="123"
$ VARSTR="\${data_file_${PARAM}}"
$ echo "${VARSTR}"
${data_file_123}
$ eval echo "$VARSTR"
sales.dat

Beware, eval carries a hidden danger:

$ PARAM="} ; touch / ; \${1"
$ VARSTR="\${data_file_${PARAM}}"
$ echo "${VARSTR}"
${data_file_} ; touch / ; ${1}
$ eval echo ${VARSTR}

touch: setting times of `/': Permission denied
$
1 Like

Corona688,

Thank you very much for replying so quickly to my post. Could you please kindly explain the first example you gave me, because I do not understand how to apply it and will like to try it.

$ NAME="VAR"
$ VAR="1234"
echo "${!NAME}"
1234
$

Something more like your code:

data_file_123="whatever"
PARAM="123"
VAR="data_file_${PARAM}"
[ -f "${!VAR}" ] && echo "The file ${!VAR} exists"
1 Like

Corona688,

Once again thank you ! I got it to work.

environment variables

data_file_123=sales.dat
data_directory=inbound

In the script

 
param1=123
file_name=data_file_$param1
eval v_file_name='$'$file_name
 
if [[ ! -f $data_directory/$v_file_name ]]; then 
.....
.....
 

THANKS FOR YOUR HELP!!!