linux - If/else 有 4 个变量

标签 linux bash variables

确保用户准确输入我想要的信息的正确方法是什么,或者以正确的期望回应声明?我有一个 bash 脚本,它有 4 个需要特定输入形式的变量,但我不知道如何检查它们的输入。

这些是我用来完成命令的变量:

read -p "Enter ID: " ID #SONGID can only be 10 digits long
read -p "Enter directory to search in e.g ab,cd,ef: " DIR #Directories are two letters and range from a-z
read -p "This abbreviation needs to match previous choice e.g ab, cd, ef: " FILE
read -p "Enter date of file e.g 20140503 or 201405*: " DATE

现在我编写脚本的方式无论如何都会继续。

SONGID="10"
if [ $(echo "SONGID" | grep -E "[0-10") ] && 
    echo "Song ID good"
else
    echo "ID needs to be 10 digits"
    exit
fi

最佳答案

您可以使用类似于以下的模式。纯 Bash。您确信当您离开 while 循环时,数据已被相应的函数验证——所以如果出现问题,您将不得不责怪该函数,而不是程序的结构<支持>1.

#!/bin/bash

validate_ID() {
    # Success if and only if $1 is a string of 10 digits
    [[ $1 =~ ^[[:digit:]]{10}$ ]]
}

validate_dir() {
    # Success if and only if $1 is a string of 2 letters in the range [a-z]
    [[ $1 =~ ^[abcdefghijklmnopqrstuvwxyz]{2}$ ]]
    # Hard-coded here for security, since depending on locales, other characters
    # would pass, e.g., é. Try it: [[ é =~ [a-z] ]]; echo $?
}

validate_file() {
    # I didn't understand the requirements... this always succeeds for now
    return 0
}

validate_date() {
    # Don't know how you want to validate this... this always succeeds for now
    return 0
}

while :; do
    IFS= read -rep "Enter ID: " songID
    history -s -- "$songID"
    validate_ID "$songID" && break
    echo "Bad ID"
done

while :; do
    IFS= read -rep "Enter directory to search in e.g ab,cd,ef: " dir #Directories are two letters and range from a-z
    history -s -- "$dir"
    validate_dir "$dir" && break
    echo "Bad dir"
done

while :; do
    IFS= read -rep "This abbreviation needs to match previous choice e.g ab, cd, ef: " file
    history -s -- "$file"
    validate_file "$file" && break
    echo "Bad file"
done

while :; do
    IFS= read -rep "Enter date of file e.g 20140503 or 201405*: " date
    history -s -- "$date"
    validate_date "$date" && break
    echo "Bad date"
done

history 命令:每个命令都会将读取的值插入到历史记录中,以便用户可以使用向上箭头(尝试使用和不使用)检索以前的值——注意 -e 标志到 read 命令以使用 readline。 TAB 补全适用于文件名。

注意。目前有两个验证函数没有完成它们的工作;我不完全明白你想如何验证数据。


1其他一些 REPL 设计可能会失败,例如,

while read a; do
    validate "$a" && break
    echo "$a is invalid"
done

看起来不错,但如果读取有错误就会失败,例如,用户可以输入任意数据,按几次 Ctrl-D,你就会在变量 a.

关于linux - If/else 有 4 个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23483511/

相关文章:

javascript - 局部函数变量更改不会影响全局范围内的变量。为什么不?

Linux:将命令添加到 bashrc 中的另一个命令

c - 当阴影在 pam_unix 中不可读时如何进行散列检查?

Linux内核源代码修改和重新编译

java - maven pom调用子目录下的其他poms

linux - Bash - 将行中的最后一个字移动到行首

bash - Shell 脚本 zenity - 检查是否取消

php - 将选择值传递给另一个页面 php

php - 如何通过 JavaScript slider 实时更改 CSS 颜色值?

c - http_proxy 是否会在 Linux 中自动为所有应用程序工作?