2014-02-22 111 views
1

这是一个示例bash作为你在两个方面看:如何检查输入是否为空格并为空或不是?

1)首先

#!/bin/bash 

number=0 
echo "Your number is: $number" 
IFS=' ' read -t 2 -p "Press space to add one to your number: " input 

if [ "$input" -eq $IFS ]; then #OR ==> if [ "$input" -eq ' ' ]; then 
    let number=number+1 
    echo $number 
else 
    echo wrong 
fi 

2)第二:

#!/bin/bash 

number=0 
echo "Your number is: $number" 
read -t 2 -p "Press space to add one to your number: " input 

case "$input" in 
    *\ *) 
     let number=$((number+1)) 
     echo $number 
     ;; 
    *) 
     echo "no match" 
     ;; 
esac 

现在的问题是:

有了这两种方法,我该如何检查输入参数是否为white spacenull

我想在bash中检查white spacenull

感谢

+0

空间不是整数。使用'='更改'-eq'以将变量与空格比较为'$ IFS'。 –

+0

你的意思是'=='OR'='? – MLSC

+1

http://stackoverflow.com/questions/13509508/check-if-string-is-neither-empty-not-space-in-shell-script – shivam

回答

1

你可以尝试这样的事情:

#!/bin/bash 

number=0 
echo "Your number is: $number" 
IFS= read -t 2 -p "Press space to add one to your number: " input 
# Check for Space 
if [[ $input =~ \ + ]]; then 
    echo "space found" 
    let number=number+1 
    echo "$number" 
# Check if input is NULL 
elif [[ -z "$input" ]]; then 
    echo "input is NULL" 
fi 
+0

对不起..没有工作 – MLSC

+1

你能详细说明什么没有工作吗?我在我的系统上测试过它。 –

+0

Owww ...是的..这是工作好..谢谢你... – MLSC

0

这部分检查输入字符串为NULL

if [ "##"${input}"##" = "####" ] 
then 
echo "You have input a NULL string" 
fi 

,这部分检查一个或多个空格caharacters被输入

newinput=$(echo ${input} | tr -s " ") # There was a typo on thjis line. should be fixed now 
if [ "##"${newinput}"##" = "## ##" ] 
then 
echo "You have input one (or more) whitespace character(s)" 
fi 

在aorder你把他们在完成所有比较后,在if - fi块中查看拟合和设置标志以进行评估。

+0

我测试了它,但出现错误:意外的EOF while寻找匹配的'}' ./j.sh:第15行:语法错误:文件意外结束 – MLSC

+0

抱歉..我犯了一个印刷错误。请看第一行,在第二部分标出。 – MelBurslan

+0

它没有错误,但不能正常工作..我通过你的解决方案更新我的文章..看到它 – MLSC