Use substituted string as a command in shell script

71 Views Asked by At

Given the variables listed below:

echo ${userupper}_PYTHON
# YTU_PYTHON
echo $YTU_PYTHON
# /home/ytu/anaconda3/bin/python
echo $path
# foo.py

Now I'd like to execute /home/ytu/anaconda3/bin/python foo.py with userupper and path. I tried $(${userupper}_PYTHON) $path but it ends up with error messages including:

YTU_PYTHON: not found
foo.py: not found

It seems like it takes $(${userupper}_PYTHON) as bare YTU_PYTHON rather than expected $YTU_PYTHON. How should I do to make it right?


Edits:

The suggested duplication should have solved my problem. However for some unknown reasons it's not working.

#!/usr/bin/env bash

for user in ytu
do
  . /home/${user}/.profile
  userupper=$(echo ${user} | awk '{print toupper($0)}')
  userpython=${userupper}_PYTHON
  cd /home/${user}/H2-ML/crons
  for path in $(ls | grep ^${user}_.*_monthly_report.py$)
  do
    echo ${userpython}
    echo $path
    echo $YTU_PYTHON
    echo ${!userpython}
  done
done

The code chunk above returns:

YTU_PYTHON
ytu_clinic249_monthly_report.py
/home/ytu/anaconda3/bin/python
send_monthly_reports.sh: 14: send_monthly_reports.sh: Bad substitution

, which makes me so confused.

1

There are 1 best solutions below

9
On BEST ANSWER

Try this:

command=${userupper}_PYTHON
echo ${!command} $path # ommit echo if you want to execute command

in your case it echos:

/home/ytu/anaconda3/bin/python foo.py

Here is link that might be useful if you want to write bash scripts. You should not parse ls output in the nutshell.

You also create unnecessary new process, both lines do the same:

$(echo ${user} | awk '{print toupper($0)}')
${user^^} #paramenter expansion