开发者

Bash script execute shell command with Bash variable as argument

开发者 https://www.devze.com 2023-03-24 12:47 出处:网络
I have one loop that creates a group of variables like DISK1, DISK2... where the number at the end of the variable name gets created by the loop and then loaded with a path to 开发者_如何学编程a devic

I have one loop that creates a group of variables like DISK1, DISK2... where the number at the end of the variable name gets created by the loop and then loaded with a path to 开发者_如何学编程a device name. Now I want to use those variables in another loop to execute a shell command, but the variable doesn't give its contents to the shell command.

for (( counter=1 ; counter<=devcount ; counter++))
do
    TEMP="\$DISK$counter"

# $TEMP should hold the variable name of the disk, which holds the device name
# TEMP was only for testing, but still has same problem as $DISK$counter

    eval echo $TEMP  #This echos correctly

    STATD$counter=$(eval "smartctl -H -l error \$DISK$counter" | grep -v "5.41" | grep -v "Joe")
    eval echo \$STATD$counter

done


Don't use eval ever, except maybe if there is no other way AND you really know what you are doing.

The STATD$counter=$(...) should give an error. That's not a valid assignment because the string "STATD$counter" is not a valid variable name. What will happen is (using a concrete example, if counter happened to be 3 and your pipeline in the $( ) output "output", bash will only expand that line as far as "STATD3=output" so it will try to find a command named "STATD3=output" and run it. Odds are this is not what you intended.

It sounds like everything you want to do can be accomplished with arrays instead. If you are not familiar with bash arrays take a look at Greg's Wiki, in particular this page or the bash man page to find out how to use them.

For example, in the loop you didn't post in your question: make disk (not DISK: don't use all upper case variable names) an array like so

disk+=( "new value" )

or even

disk[counter]="new value"

Then in the loop in your question, you can make statd an array as well and assign it with values from disk by

statd[counter]="... ${disk[counter]} ..."

It's worth saying again: avoid using eval.

0

精彩评论

暂无评论...
验证码 换一张
取 消