Thursday, October 28, 2021

[SOLVED] Using select statement to repeat process in bash script

Issue

I'm super close to finishing my assignment but I'm a little stumped on one part.

Here's what I got:

for file in $1
do
    wget "$1" -O "output-$1.html" -q
    cat output-$1.html | grep -o '<a .*href=.*>' | 
    sed -e 's/<a /\n<a /g' | 
    sed -e 's/<a .*href=['"'"'"]//' -e 's/["'"'"'].*$//' -e '/^$/ d' | 
    grep 'http' > ~/bcache/$1.bcache

select LINK in `cat ~/bcache/$1.bcache` "q_to_quit"
    do
        if [ $LINK = "q_to_quit" ] 
           then
             exit 1
           else 
               repeat lines 3-7
        fi
    done

Lines 3-7 take a url and output to an html file, where that html file is then sorted through with grep and sed to only pull out "http://...", which is then put into a file which is stored into a directory called bcache.

The select statement prints out all of the "http://..." with numbers preceding them, with the last option being q_to_quit.

I can't figure out how to repeat the process of lines 3 through 7 once someone enters a number (which corresponds to a url, which needs to be sorted, saved, and stored, rinse and repeat.)


Solution

Your for loop will only loop once (ideally) since $1 should only be a single word (and should be quoted, "$1", to ensure that whatever the value you are given is used correctly).

So you probably don't need it.

If you were trying to have that support multiple arguments being passed to the script then you want for file in "$@" (or just for file which is the same thing) but this doesn't really work well with the rest of the scripts operation it seems to me.

Given the above to get the effect you actually want you put the loop body in a while true or while : loop and using $LINK in those top lines instead of $1.

LINK=$1

while :; do
    wget "$LINK" -O "output-$LINK.html" -q
    cat "output-$LINK.html" | grep -o '<a .*href=.*>' | 
    sed -e 's/<a /\n<a /g' | 
    sed -e 's/<a .*href=['"'"'"]//' -e 's/["'"'"'].*$//' -e '/^$/ d' | 
    grep 'http' > ~/bcache/"$LINK.bcache"

    select LINK in `cat ~/bcache/"$LINK.bcache"` "q_to_quit"
    do
        if [ $LINK = "q_to_quit" ] 
        then
            exit 1
        else 
            break
        fi
    done
done

Also, as I just put in a comment on the OP you shouldn't Read Lines With for.



Answered By - Etan Reisner