linuxbashwhile-loopline-by-line

"read" command not executing in "while read line" loop


First post here! I really need help on this one, I looked the issue on google, but can't manage to find an useful answer for me. So here's the problem. I'm having fun coding some like of a framework in bash. Everyone can create their own module and add it to the framework. BUT. To know what arguments the script require, I created an "args.conf" file that must be in every module, that kinda looks like this:

LHOST;true;The IP the remote payload will connect to.
LPORT;true;The port the remote payload will connect to.

The first column is the argument name, the second defines if it's required or not, the third is the description. Anyway, long story short, the framework is supposed to read the args.conf file line by line to ask the user a value for every argument. Here's the piece of code:

info "Reading module $name argument list..."
while read line; do
    echo $line > line.tmp
    arg=`cut -d ";" -f 1 line.tmp`
    requ=`cut -d ";" -f 2 line.tmp`
    if [ $requ = "true" ]; then
        echo "[This argument is required]"
    else
        echo "[This argument isn't required, leave a blank space if you don't wan't to use it]"
    fi
    read -p " $arg=" answer
    echo $answer >> arglist.tmp
done < modules/$name/args.conf
tr '\n' ' ' < arglist.tmp > argline.tmp
argline=`cat argline.tmp`
info "Launching module $name..."
cd modules/$name
$interpreter $file $argline
cd ../..
rm arglist.tmp
rm argline.tmp
rm line.tmp
succes "Module $name execution completed."

As you can see, it's supposed to ask the user a value for every argument... But:

1) The read command seems to not be executing. It just skips it, and the argument has no value

2) Despite the fact that the args.conf file contains 3 lines, the loops seems to be executing just a single time. All I see on the screen is "[This argument is required]" just one time, and the module justs launch (and crashes because it has not the required arguments...).

Really don't know what to do, here... I hope someone here have an answer ^^'. Thanks in advance!

(and sorry for eventual mistakes, I'm french)

Alpha.


Solution

  • As @that other guy pointed out in a comment, the problem is that all of the read commands in the loop are reading from the args.conf file, not the user. The way I'd handle this is by redirecting the conf file over a different file descriptor than stdin (fd #0); I like to use fd #3 for this:

    while read -u3 line; do
        ...
    done 3< modules/$name/args.conf
    

    (Note: if your shell's read command doesn't understand the -u option, use read line <&3 instead.)

    There are a number of other things in this script I'd recommend against: