Home Bash: Gathering all inputs at once, without waiting for the process to end
Reply: 1

Bash: Gathering all inputs at once, without waiting for the process to end

Dantalion
1#
Dantalion Published in 2017-11-13 16:39:05Z

I have been writing a bash script in which the process depends on the user's input, but it is a 1min process, and if the user wants to do it more than once, he will have to wait for the loop to finish. Here is the code:

while [[ ! "$addstr" =~ ^[Nn](.*)?$ ]]; do
    read -p "[*] String to permute around: " string
    echo; sleep 0.1s

    while [[ ! "$string" =~ ^[0-9a-zA-Z]+$ ]]; do
        echo "[!] Only alphanumeric strings are allowed!"; sleep 0.1s
        read -p "=> " string
        echo; sleep 0.1s
    done

    ## PROCESS ##

    echo "[?] Do you want to permute around another string?"; sleep 0.1s
    read -p "=> " addstr
    echo; sleep 0.1s

    while [[ ! "$addstr" =~ ^[YyNn](.*)?$ ]]; do
        echo "[!] Type again:"
        read -p "=> " addstr
        echo; sleep 0.1s
    done
done

What i want to do is to allow the user to enter all strings AT ONCE, storing the variables for each of them and running the process as many times as it needs... I tryed a lot of things, even appending a "$counter" after "$string" but couldn't make this work, i believe it's something very simple and i just don't have the knowledge..

glenn jackman
2#
glenn jackman Reply to 2017-11-13 20:19:43Z

Alter the script to read input from stdin. Then the user can redirect from a file.

Your script then becomes:

while IFS= read -r string; do
    if [[ ! "$string" =~ ^[0-9a-zA-Z]+$ ]]; do
        echo "[!] Only alphanumeric strings are allowed! $string"
        continue
    fi

    ## PROCESS ##
done

And the user types something like

./yourscript < file.with.strings

or various other ways to feed data to your script's stdin.


Another thought: gather all the inputs up front:

inputs=()
while true; do
    read -p "[*] String to permute around: " string
    echo; sleep 0.1s

    while [[ ! "$string" =~ ^[[:alnum:]]+$ ]]; do
        echo "[!] Only alphanumeric strings are allowed!"; sleep 0.1s
        read -p "=> " string
        echo; sleep 0.1s
    done

    # store the user input
    inputs+=( "$string" )

    echo "[?] Do you want to permute around another string?"; sleep 0.1s
    read -p "=> " addstr
    echo; sleep 0.1s

    while [[ ! "$addstr" =~ ^[[:blank:]]*[YyNn] ]]; do
        echo "[!] Type again:"
        read -p "=> " addstr
        echo; sleep 0.1s
    done

    [[ "$addstr" =~ ^[[:blank:]]*[Nn] ]] && break
done

## PROCESS ##
for string in "${inputs[@]}"; do
    process "$string"
done
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.300657 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO