我正在尝试创建一个 if else 语句来验证用户是否输入了某些内容。如果他们有它应该运行命令,如果没有我想回显帮助语句。
答案1
一个例子(相当简单)如下。将创建一个名为 userinput 的文件,其中包含以下代码。
#!/bin/bash
# create a variable to hold the input
read -p "Please enter something: " userInput
# Check if string is empty using -z. For more 'help test'
if [[ -z "$userInput" ]]; then
printf '%s\n' "No input entered"
exit 1
else
# If userInput is not empty show what the user typed in and run ls -l
printf "You entered %s " "$userInput"
ls -l
fi
要开始学习 bash,我建议您查看以下链接http://mywiki.wooledge.org/
答案2
如果您想知道用户是否输入了特定字符串,这可能会有所帮助:
#!/bin/bash
while [[ $string != 'string' ]] || [[ $string == '' ]] # While string is different or empty...
do
read -p "Enter string: " string # Ask the user to enter a string
echo "Enter a valid string" # Ask the user to enter a valid string
done
command 1 # If the string is the correct one, execute the commands
command 2
command 3
...
...
答案3
当多个选择有效时,做一个while条件来匹配正则表达式:
例如:
#!/bin/bash
while ! [[ "$image" =~ ^(rhel74|rhel75|cirros35)$ ]]
do
echo "Which image do you want to use: rhel74 / rhel75 / cirros35 ?"
read -r image
done
它将不断要求输入,直到输入三个选项之一。