bash - 用于检查字符串和特殊字符的 shell 脚本

标签 bash shell

我正在编写一个示例 shell 脚本,如果字符串不等于“sample”并且字符串不包含特殊字符,我必须执行一些操作。我尝试了下面的代码,但出现语法错误。这是正确的做法吗?如果不是,正确的做法是什么?

#!/bin/bash
  str='sudo'
  if [ "$str" != "sample" ] && [[ "$str" != *['!'@#\$%^\&*()_+]* ]]
  then
      echo "Proceed"
  else
       echo "Stop"
  fi

我遇到这样的语法错误:

bash-3.2$ ./test.sh
./test.sh: line 3: syntax error in conditional expression: unexpected token `('
./test.sh: line 3: syntax error near `&*()'
./test.sh: line 3: `if [ "$str" != "sample" ] || [[ "$str" != *['!'@#\$%^\&*()_+]* ]]'

最佳答案

这可能是一个替代方案

#!/bin/bash
 str='sudo'
 if ! [ "$str" = "sample" ] && ! [[ "$str" =~ [^[:alnum:]]+ ]]
 then
   echo "Proceed"
 else
   echo "Stop"
 fi

注意

  1. 检查 bash [ character classes ] .
  2. 字符类之前的 ^ 否定它,本质上我们正在寻找字母数字以外的任何内容
  3. 类似地,在测试表达式否定它之前!
  4. + 检查至少出现一次。

关于bash - 用于检查字符串和特殊字符的 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38377805/

相关文章:

linux - GNU Parallel - 将输出重定向到具有特定名称的文件

Python 2.6 在 Ubuntu 上导入包 (psyco)

linux - 在 telnet session 中使用变量

android - 无法在android shell中执行shell脚本

json - 无法在 shell 脚本中使用 jq 获取 JSON 数组值

bash 日期最后带有周数

mysql - 如何使用shell脚本获取mysql的增量备份

linux - 如何在 bash 中循环遍历一系列十进制数?

Bash:猫和 echo 之间的区别

windows - 使用 Windows 命令行查看文件是否存在并重命名