【问题标题】:How to check if input is white space and null or not?如何检查输入是否为空格和空值?
【发布时间】:2014-02-22 18:02:41
【问题描述】:

这是一个示例 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 space还是null

我想在 bash 中同时检查 white spacenull

谢谢

【问题讨论】:

  • 空格不是整数。将 -eq 更改为 = 以将带空格的变量与 $IFS 进行比较。
  • 你的意思是 ===?
  • 我想知道它是否为空数字不会改变值..但如果是空白数字会增加
  • @MortezaLSC 字符串比较没有区别。 Bourne shell 支持=,Bash 支持==。但它们在 bash 中是同义词。

标签: linux bash if-statement input


【解决方案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

【讨论】:

  • 你能详细说明什么不起作用吗?我在我的系统上对其进行了测试。
  • 为什么不只是 ((number++)) ?此外,您没有检查所有空白字符,只检查常规空格。您可以使用此 [[ $input = *+([[:space:]])* ]] 检查与 extglob 代替。或者这个正则表达式[[ $input =~ [[:space:]]+ ]]。但也可能是您只想要常规空间。
【解决方案2】:

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

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

这部分检查是否输入了一个或多个空白字符

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

按照您认为合适的顺序组合它们,并在 if --fi 块中设置标志以在完成所有比较后进行评估。

【讨论】:

  • 我测试过,但是出现了错误:在寻找匹配的`}'时出现意外的EOF ./j.sh:第15行:语法错误:文件意外结束
  • 对不起.. 我犯了一个印刷错误。请看第一行,标记在第二部分。
  • 它没有错误但不能正常工作..让我用你的解决方案更新我的帖子..看看它
  • 当您运行我的脚本版本并按空格键然后按回车键时,您会得到什么? “1”或“错误”
  • 我注意到,您指定了 2 秒的时间间隔让用户输入他/她的输入,但没有字符串长度。尝试echo "Press space to add one to your number: "; read -n 1 input 而不是您的输入行
猜你喜欢
  • 1970-01-01
  • 2020-09-16
  • 2018-05-26
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 2013-01-05
  • 1970-01-01
相关资源
最近更新 更多