Arthur Alves
Arthur Alves

Reputation: 458

Shell Script - Doesn't access contents of variables

I'm writing a Shell Script and an unexpected error (that I never saw before) appears.

The code is something like this:

 num=1

 case $line in
    *.mp3*)
    s$num=$total_seconds; # $total_seconds is a variable with numbers like: 11.11
    a$num=$file;
    num=$(($num + 1));
    ;;
 esac

If I try to see the contents of these variables it doesn't show anything.

echo $s1 $a1
echo $s2 $a2

or even:

for ((i=1; i<=$num; i++))
do
  echo $s$i $a$i
done

Upvotes: 0

Views: 103

Answers (2)

chepner
chepner

Reputation: 530882

bash only recognizes a variable assignment if the LHS is a literal, not an expression. While you could modify your code slightly to have such dynamically generated variable names:

num=1

case $line in
  *.mp3*)
  declare s$num=$total_seconds; # $total_seconds is a variable with numbers like: 11.11
  declare a$num=$file;
  num=$(($num + 1));
  ;;
esac 

a better idea is to use an array as suggested by kojiro.

To access them dynamically, you'll need to use indirect expansion:

num=1
var="s$num"
echo ${!var}  # var must be the name of a variable, not any other more complex expression

Upvotes: 2

kojiro
kojiro

Reputation: 77059

If you're OK with using bash (or any shell that supports arrays), then use arrays:

num=1
declare -a s
declare -a a
case $line in
    *.mp3*)
        s[num]=$total_seconds # $total_seconds is a variable with numbers like: 11.11
        a[num++]=$file
        ;;
esac

If you want something POSIXly strict, then things get tougher. I don't want to make any suggestions about that without knowing more about your code.

Aside: $total_seconds is a variable with strings like 11.11. These shells don't support floating point numbers.

Upvotes: 2

Related Questions