Bash:立即收集所有输入,无需等待流程结束

时间:2017-11-13 16:39:06

标签: bash variables while-loop append user-input

我一直在编写一个bash脚本,其中进程取决于用户的输入,但它是一个1分钟的进程,如果用户想要多次执行,他将不得不等待循环完成。 这是代码:

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

我想要做的是允许用户输入AT ONCE中的所有字符串,为每个字符串存储变量并根据需要多次运行该过程...我尝试了很多东西,甚至附加了一个“$ counter”之后的“$ counter”却无法完成这项工作,我相信这很简单,我只是没有这方面的知识..

1 个答案:

答案 0 :(得分:1)

更改脚本以从stdin读取输入。然后,用户可以从文件重定向。

然后您的脚本变为:

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

    ## PROCESS ##
done

用户输入类似

的内容
./yourscript < file.with.strings

或其他各种方式将数据提供给脚本的标准输入。

另一个想法:预先收集所有输入:

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