I have a problem with my bash array I was trying to read the file however the array allocated it in array[1] instead of 0
#!/bin/bash
index=0
INPUT=BookDB.txt
OLDIFS=$IFS
IFS=:
i=0
book=()
[ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99; }
while read bookname author price quantity sold
do
#echo "BookName : $bookname"
#echo "Author : $author"
#echo "Price : $price"
#echo "Quantity : $quantity"
#echo "Sold : $sold"
book+=("$bookname")
author+=("$author")
price+=("$price")
quant+=("$quantity")
sold+=("$sold")
done < $INPUT
IFS=$OLDIFS
# Use c style for loop
# get total subscripts in an array
total=${#book[*]}
#
for (( i=0; i<=$(( $total -1 )); i++ ))
do
echo $i "${book[$i]} "
done
total=${#author[*]}
#
for (( i=0; i<=$(( $total -1 )); i++ ))
do
echo $i "${author[$i]} "
done
Here is the output of the file
Book
0 Harry Potter - The Half Blood Prince
1 The little Red Riding Hood
2 Harry Potter - The Phoniex
3 Harry Potter - The Deathly Hollow
4 Little Prince
5 Lord of The Ring
6 Three Little Pig
7 All About Ubuntu
8 Catch Me If You Can
9 Happy Day
Author
0
1 J.K Rowling
2 Dan Lin
3 J.K Rowling
4 Dan Lin
5 The Prince
6 Johnny Dept
7 Andrew Lim
8 Ubuntu Team
9 Mary Ann
10 Mary Ann
Somehow the array for author[0] is empty
bash
andksh
, arrays just extend scalar variables.$author
is${author[0]}
,author=x
orread author
is assigning toauthor[0]
. Use different variable names in yourread
statement. – Stéphane Chazelas Jan 27 at 13:08perl
orawk
for that rather thanbash
loops and arrays. – Stéphane Chazelas Jan 27 at 13:38