1

I dont seem to be able assign a bunch of variables in my shell script. Im trying to assign HOST1,HOST2,HOST3 to three different machine names.

My script is as follows:

   #!/bin/bash
   #
   set -vx

   FIXHOSTS=`cat /tmp/fixHosts.txt`
   NUMBER=1
   NUMBEROFHOSTS=`cat /tmp/fixHosts.txt | wc -l`

   for line in $FIXHOSTS
   do 
   HOST$NUMBER=$line
   echo $HOST1
   ((NUMBER = $NUMBER + 1)) 
   done

   echo $HOST1
   echo $HOST2
   echo $HOST3
   echo $HOST4

fixHosts.txt contains the following:

      wayne-000
      wayne-002
      wayne-003

This is the output I get:

for line in $FIXHOSTS
do 
HOST$NUMBER=$line
echo $HOST1
((NUMBER = $NUMBER + 1))
done
+ for line in '$FIXHOSTS'
+ HOST1=wayne-000
fvwmtest.sh: line 15: HOST1=wayne-000: command not found
+ echo

+ (( NUMBER = 1 + 1 ))
+ for line in '$FIXHOSTS'
+ HOST2=wayne-002
fvwmtest.sh: line 15: HOST2=wayne-002: command not found
+ echo

+ (( NUMBER = 2 + 1 ))
+ for line in '$FIXHOSTS'
+ HOST3=wayne-003
fvwmtest.sh: line 15: HOST3=wayne-003: command not found
+ echo

+ (( NUMBER = 3 + 1 ))

#done

echo $HOST1
+ echo

echo $HOST2
+ echo

echo $HOST3
+ echo

echo $HOST4
+ echo

Why don't they echo? Why are they not getting assigned?

nrs90
  • 168
  • 1
  • 3
  • 19
  • 1
    Bash doesn't support dynamic variables, this is a job for an array. @fedorqui That isn't relevant as OP is addressing the variables by full names. – 123 Nov 24 '15 at 13:58
  • You *can* do this with `printf -v` and `declare` but don't. Just use an array. Also [Don't read lines with `for`](http://mywiki.wooledge.org/DontReadLinesWithFor) and if you read the file into an array originally you wouldn't have any of these problems or need to do anything beyond that in the first place. See [Bash FAQ 001](http://mywiki.wooledge.org/BashFAQ/001) for how to read a file line-by-line and [Bash FAQ 005](http://mywiki.wooledge.org/BashFAQ/005#Loading_lines_from_a_file_or_stream) for how to read a file into an array. – Etan Reisner Nov 24 '15 at 14:05

1 Answers1

0

dynamic variables can be quite annoying in bash. The declare command can help:

$ num=13
$ val="hello world"
$ declare "host$num=$val"
$ echo $host13
hello world

So you want:

num=0
while read -r line; do
    ((num++))
    declare host$num="$line"
done < /tmp/fixHosts.txt
num_hosts=$num

echo $host1 $host2 $host3 ...

Notes:

Even simpler is to use an array: if you have bash version 4

mapfile -t hosts < /tmp/fixHosts.txt
num_hosts=${#hosts[@]}
echo ${hosts[0]} ${hosts[1]} ${hosts[2]} ...
Community
  • 1
  • 1
glenn jackman
  • 238,783
  • 38
  • 220
  • 352