Aliyow
Aliyow

Reputation: 1

What am I doing wrong in my script?

I wrote this script that is suppose to read a file line by line and then do a while loop and set the output as an array, but for some reason my script doesn't wait for user input before it continues, it automatically choses 0.

#!/usr/bin/bash

declare -a ArrayBox


filename="text.txt"
exec 10<&0

exec < $filename

x=0
while read line
do
    ArrayBox[$x]=$line
    echo "[$x] $line"
    let x++

    if [[ $x -eq 5 ]]
    then

        echo  "Enter your chose: "; read num; 
        echo "you chose ${ArrayBox[$num]}"

    fi


done


#Output
[0] as
[1] ag
[2] sd
[3] gh
[4] tr
Enter your chose: 
you chose as
[5] fg
[6] fg

Upvotes: 0

Views: 51

Answers (3)

riteshtch
riteshtch

Reputation: 8769

You are duplicating stdin fd number 0 to 10 and setting stdin to file. So all further inputs for read (both for while and num) are meant to come from the file. Since you don't intend to provide data for the 2nd read via file, it takes the default value which you have set earlier i.e 0. In this case you need to explicitly tell read to read from stdin (the duplicated fd which you had made earlier i.e fd 10)

from help read here is the way:

-u fd read from file descriptor FD instead of the standard input

#!/bin/bash

declare -a array=()
declare -i x=0

exec 10<&0
exec < "input_file.txt"

while IFS='' read -r line || [[ -n "$line" ]]
do
    array+=("$line")
    echo "[$x] $line"
    x=$((x+1))

    if [[ $x -eq 5 ]]
    then
        echo 'Enter your choice: '
        read -u 10 choice
        echo "You chose: ${array[$choice]}";
    fi
done 

And here is the output:

$ cat -n input_file.txt 
     1  line1
     2  line2 abcd
     3  line3 abc
     4  line4 ab
     5  line5 a
     6  line6 
     7  line7
$ ./script.bash 
[0] line1
[1] line2 abcd
[2] line3 abc
[3] line4 ab
[4] line5 a
Enter your choice: 
3
You chose: line4 ab
[5] line6 
[6] line7
$

Edit: as Huihoo pointed out you can use read -u 10 num or read num <&10 to read from fd 10. Thanks Huihoo

Upvotes: 2

Huihoo
Huihoo

Reputation: 133

You can replace read num with read -u 10 num or read num <&10, both work.

Upvotes: 0

SergeiMinaev
SergeiMinaev

Reputation: 296

You can use sed to read specific line from file (first line number is 1, not 0). An example:

#!/usr/bin/bash
declare -a ArrayBox
filename="text.txt"
x=1
while true
do  
    line=`sed "${x}q;d" ${filename}`
    ArrayBox[$x]=$line
    echo "[$x] $line"
    let x++

    if [[ $x -eq 6 ]]
    then

        echo  "Enter your chose: "; read num; 
        echo "you chose ${ArrayBox[$num]}"
        break

    fi
done

Upvotes: 0

Related Questions