PatelisGM
PatelisGM

Reputation: 37

Bash Scripting - Variable Concatenation

Completely new to Linux and Bash scripting and I've been experimenting with the following script :

declare -a names=("Liam" "Noah" "Oliver" "William" "Elijah")
declare -a surnames=("Smith" "Johnson" "Williams" "Brown" "Jones")
declare -a countries=()
readarray countries < $2
i=5
id=1
while [ $i -gt 0 ]
do
  i=$(($i - 1))
  rname=${names[$RANDOM % ${#names[@]}]}
  rsurname=${surnames[$RANDOM % ${#surnames[@]}]}
  rcountry=${countries[$RANDOM % ${#countries[@]}]}
  rage=$(($RANDOM % 5))
  record="$id $rname $rsurname $rcountry"
  #record="$id $rname $rsurname $rcountry $rage"
  echo $record
  id=$(($id + 1))
done

The script above produces the following result :

1 Liam Williams Andorra
2 Oliver Jones Andorra
3 Noah Brown Algeria
4 Liam Williams Albania
5 Oliver Williams Albania

but the problem becomes apparent when the line record="$id $rname $rsurname $rcountry" gets commented and the line record="$id $rname $rsurname $rcountry $rage" is active where the exact output on the second execution is :

 4William Johnson Albania
 2Elijah Smith Albania
 2Oliver Brown Argentina
 0William Williams Argentina
 3Oliver Brown Angola

The file I am reading the countries from looks like this :

Albania
Algeria
Andorra
Angola
Argentina

Could you provide an explanation to why this happens?

Upvotes: 0

Views: 43

Answers (1)

larsks
larsks

Reputation: 312808

Your countries input file has DOS-style <cr><lf> (carriage-return line-feed) line endings.

When you read lines from the file, each element of the countries array ends up looking like somename<cr>, and when printed the <cr> moves the cursor back to the beginning of the line, so the contents of $rage end up overwriting the beginning of the line.

The fix is to convert your countries input to use Unix style (<lf> only) line endings. You can do this with dos2unix <inputfile> > <outputfile>, for example.

Upvotes: 2

Related Questions