variables - bash indirect reference by reference -


a lot of similar questions, hadn't found 1 using variable in name way:

#!/bin/bash  # $1 should 'dev' or 'stg'  dev_path="/path/to/123" stg_path="/path/to/xyz"  # use $1 input determine path variable 'execute' ${!\$1'/morepath'} 

using $1, want able reference either $dev_path or $stg_path ($1 == 'dev' or $1 == 'stg') , able reference value of $1_path '/path/to/123' or '/path/to/xyz'

so result either be:

'/path/to/123/morepath' or '/path/to/xyz/morepath' 

based upon $1 being 'dev' or 'stg'.

i've tried various iterations of using ! , \$ in various places other posts, no luck

i think unsafe. if $1 gets value that's not dev or stg cause syntax error , other unexpected things may happen. eval wouldn't idea unless add conditional filter. use case statement:

case "$1" in dev)     "$dev_path"/bin/execute     ;; std)     "$std_path"/bin/execute     ;; *)     echo "invalid argument: $1"     ;; esac 

or make sure it's valid , use eval:

[[ $1 == dev || $1 == std ]] && eval "\"\${${1}_path}/bin/execute\"" 

using if ... elif ... valid case method simpler.

as variable indirection need store "${1}_path" variable first unnecessary.

you use dev|std) eval ... ;; in case statement @ preference.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -