【问题标题】:how to check if input is number or alphabet in GNU bash如何在 GNU bash 中检查输入是数字还是字母
【发布时间】:2020-04-13 07:00:56
【问题描述】:

我在 GNU sed 命令中遇到意外的“如果”和“然后”错误。如何连续检查输入。请帮助我

if ! [[ "$versionCode" =~ ^[0-9]+$ ]]
then
    echo "Sorry integers only"
fi

这是我的错误

sh: 1: Syntax error: end of file unexpected (expecting "then")

sh: 1: Syntax error: "then" unexpected

Sorry integers only
sh: 1: Syntax error: "fi" unexpected

更新:

echo "Enter version code" 
read versionCode
case "$versionCode" in
   (*[!0-9]*) echo "Sorry integers only";;
   ("")       echo "Empty is not a version code";;
   (*)        echo "do something with $versionCode";;
 esac
echo "$versionCode"
sudo  sed "s/\(versionCode[[:space:]]*\)[0-9]*/\1${versionCode}/" Version.gradle

这是我的错误

Enter version code
4

sh: 1: Syntax error: end of file unexpected (expecting ")")

sh: 1: Syntax error: word unexpected

sh: 1: Syntax error: word unexpected

sh: 1: Syntax error: word unexpected

sh: 1: Syntax error: "esac" unexpected

【问题讨论】:

  • @Cyrus 对不起,我不明白,请解释一下
  • :我在您发布的代码中没有看到任何sed 命令。此外,[[ .... ]] 在 POSIX shell 中无效。
  • 试试这个:grep -q $'\r' your_script.sh && echo "carriage return found"
  • 你的代码在 Linux Ubuntu 下运行,我无法在 Win10 WSL 中测试。

标签: shell carriage-return


【解决方案1】:

POSIXly 可移植的方式是

 case "$versionCode" in
   (*[!0-9]*) echo "Sorry integers only";;
   ("")       echo "Empty is not a version code";;
   (*)        echo "do something with $versionCode";;
 esac

【讨论】:

  • @Manoj 是的,它确实有效。如果它不适合你,那么你做错了什么。请具体说明您对我的脚本所做的操作以及收到的错误消息。 “不起作用”不是一个有用的描述。你在什么系统上?你用的是哪个编辑器?
  • @jeans 我正在使用 GNU sed 脚本,我用我得到的错误更新我的脚本,我正在使用 ubuntu 作为 Windows 子系统
  • @Manoj 一个问题可能是 Windows (\r\n) 与 Unix (只是 \n) 上的行尾。尝试上面建议的 Cyrus 命令。任何输出都是行结束不匹配的标志。
猜你喜欢
  • 2013-08-05
  • 2020-03-20
  • 2012-12-23
  • 2011-09-01
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多