我正在编写一个bash脚本,该脚本需要多个用户输入。在脚本执行任何操作之前,我想确保所有值都已由用户添加。
#/bin/bash
read -p "Please enter the domain Name: " domain
read -p "Please Enter path where you want to save your result: " path
if [[ -z "$domain" && "$path"]]; then
echo "You have not entered the Domain Name"
exit 1
else
echo "Do Something Here"
fi
我检查了1个用户输入,但工作正常,但是尝试2个用户输入时,出现错误。
./test.sh: line 5: unexpected token `;', conditional binary operator expected
./test.sh: line 5: syntax error near `;'
./test.sh: line 5: `if [[ -z "$domain" && "$path"]]; then'
谢谢!
答案 0 :(得分:0)
由于语法错误,因为您忘记在"$path"
和]
之间放置空格(bash使用空格作为定界符)。
如果要在至少一种情况不正确时失败,则应使用||
(OR)运算符。
#/bin/bash
read -p "Please enter the domain name: " domain
read -p "Please enter the path where you want to save your result: " path
if [[ -z "$domain" ]] || [[ -z "$path" ]] ; then
echo "You didn't enter the domain name or the save path"
exit 1
else
echo "Do something here"
fi
答案 1 :(得分:0)
由于您使用的是[[
double brackets,因此可以使用||
来测试您的两个条件是否为真。在这种情况下,您的代码将如下所示:
#!/usr/bin/env bash
read -p "Please enter the domain Name: " domain
read -p "Please Enter path where you want to save your result: " path
if [[ -z "$domain" || -z "$path" ]]; then
echo "Either you have not entered the Domain Name, or you have not entered the path."
exit 1
else
echo "Do Something Here"
fi
请注意,括号内必须有空格。 正如其他人所指出的那样,错误应该是特定的,因此您应该考虑以下内容:
if [[ -z "$domain" ]]; then
echo "You have not entered the Domain Name"
exit 1
elif [[ -z "$path" ]]; then
echo "You have not entered the path"
exit 1
fi
echo "Do something here"
有点冗长,但可以为用户提供更具体的反馈。