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

0

1 Answer 1

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}"
3
  • but now how would echo the value of variable dynamically $(status_$hdd). This is not working, Thanks for above solution atleast. Commented Oct 29, 2017 at 13:37
  • @user2642486 See my edit Commented Oct 29, 2017 at 13:46
  • unix.stackexchange.com/questions/98419/… I found in reference too eval "echo \"\$filemsg$word1\"" Thanks again Commented Oct 29, 2017 at 13:49

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.