0

i want to write a shell script

cd /dev
for hdd in sd*; do
    [ -f "$hdd" ] || continue
    status_$hdd=$(my_def_get_hddstaus "$hdd")       #my_def_get_hddstaus returns OK or FAIL randomly just to test   
done

i get error like

status_sda0=OK: command not found
status_sda1=FAIL: command not found

I want to record the value OK or Fail into these variable, I am using bash, what I am doing wrong.

if I write status_sda0=OK in shell it record OK into status_sda0

kdm6389
  • 11

1 Answers1

0

If the variable name is not a static string (or rather: If the part before the = contains anything not allowed in a variable name) then the assignment is not recognized as such.

You need eval:

tmp_var="$(my_def_get_hddstaus "$hdd")"
eval status_$hdd=\""$tmp_var"\"

edit

You can echo the value using eval again or using indirection:

eval echo \"\$status_$hdd\"

or

var_name="status_$hdd"
echo "${!var_name}"
Hauke Laging
  • 90,279
  • but now how would echo the value of variable dynamically $(status_$hdd). This is not working, Thanks for above solution atleast. – kdm6389 Oct 29 '17 at 13:37
  • @user2642486 See my edit – Hauke Laging Oct 29 '17 at 13:46
  • https://unix.stackexchange.com/questions/98419/creating-variable-using-variable-value-as-part-of-new-variable-name

    I found in reference too eval "echo "$filemsg$word1""

    Thanks again

    – kdm6389 Oct 29 '17 at 13:49