4

I'm trying to determine the existing HDDs in each system using a for loop as show below, the problem is when I try to set the variable using the below code i get sda=true: command not found. What is the proper way to do this?

#!/bin/bash
for i in a b c d e f
do
    grep -q sd$i /proc/partitions
    if [ $? == 0 ]
    then
        sd$i=true
    else
        sd$i=false
    fi
done
2
  • declare sd$i=true So there is one catch I have found with this. When I use this in a function, the variable is null outside of the function. How do I get around this? Commented Mar 9, 2011 at 19:20
  • you would use export in this case. (I have updated my answer.) Commented Mar 10, 2011 at 19:42

3 Answers 3

3

You need to use an array or declare:

declare sd$i=true
Sign up to request clarification or add additional context in comments.

Comments

2

I would use an array in this case. For example:

$ i=a
$ sd[$i]=true
$ echo ${sd[a]}
true

As another poster stated, if you want to do this without an array, you can instead make a local variable by using syntax like declare sd$i=true. If you want to make a global variable, use export sd$i=true.

2 Comments

Unless you're using Bash 4 and associative arrays (declare -A sd), the index will resolve to 0 (unless a is a variable that ultimately resolves to a number). for i in {a..f}; do unset $i; sd[i]=true; done; declare -p sd will result in "declare -a sd='([0]="true")'" (only one element).
@Dennis, thanks for the heads up. (I was testing with bash 4.1.5.)
0

BASH FAQ entry #6: "How can I use variable variables (indirect variables, pointers, references) or associative arrays?": "Assigning indirect/reference variables"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.