【问题标题】:Shell scripting: test if a string contains a character (including chars like '*' and '\') [duplicate]Shell脚本:测试字符串是否包含字符(包括'*'和'\'等字符)[重复]
【发布时间】:2016-10-19 16:37:49
【问题描述】:

在一个 shell 脚本中,我有一个函数afun,它被传递了几个参数。 我需要另一个函数来帮助我找出这些参数中的至少一个是否包含先验未知的给定字符(但它可以是任何字符,如a9*\ , |, /, (, [ 等等,但不是space):

afun() {
  # Some commands here...
  testchar=... # here I have some logic which decides what character should be tested below
  # Now, call another function to test if any of the args to "afun"
  # contain the character in var "testchar".
  # If it does, print "Found character '$testchar' !"
}

建议的函数应该至少兼容 Bash、Dash、AshZSH - 因为我有一个需要运行的脚本在 Docker 容器中安装的不同 Linux 发行版(Ubuntu、Alpine Linux)下,我不想声明对特定 shell 解释器的依赖,因为并非所有这些容器都必须安装它。

【问题讨论】:

  • Bash、Dash、Ash 和 ZSH 。这听起来像你在开玩笑。 ;) 而且问题不是很清楚..
  • ZSH的功能比Ash还多,但我问的有道理吗?谢谢,我已经修复了变量名(应该是 testchar 而不是 c
  • 不是不合理,但恕我直言应该很难.. :(
  • @Elifarley,这不仅仅是“更多功能”——ash、bash 和 ksh 符合 POSIX sh(除了 bash 对 echo -e 的支持等警告),而 zsh 故意与标准不兼容(在其维护者决定的地方 - 事实上有一些基础 - 该标准强制执行错误的设计决策)除非在非默认 posix 模式下运行。这并不是说无法编写与 zsh 和 POSIX 兼容的 shell 兼容的脚本,但这确实意味着它需要比仅遵循 POSIX 的通常 (ash+bash+ksh) 实践更加小心。
  • 顺便说一句,local 不是由 POSIX 定义的——如果你想获得最大的兼容性,你会想要不这样做。

标签: string bash shell sh


【解决方案1】:

这是我建议的 shell 函数:

charexists() {
  char="$1"; shift
  case "$*" in *"$char"*) return;; esac; return 1
}

你可以这样使用它:

afun() {
  # Some commands here...
  testchar=... # here I have some logic which decides what character should be tested below
  # Now, call another function to test if any of the args to "afun"
  # contain the character in var "testchar".
  # If it does, print "Found character '$testchar' !"
  charexists "$testchar" "$@" && echo "Found character '$testchar' !"
}

这是一个简单的单元测试:

fun2test=charexists
{ $fun2test '*' 'a*b' && printf 1 ;} ; \
{ $fun2test '*' 'a' '*' '\' 'b#c|+' '\' && printf 2 ;} ;\
{ $fun2test '\' 'a' '*' '\' 'b#c|+' '\' && printf 3 ;} ;\
{ $fun2test '*' 'ab' || printf 4 ;} ; \
{ $fun2test '*' 'a' '' '/' 'b#c|+' '\' || printf 5 ;}; echo

如果所有 5 个测试都通过,它应该打印 12345

我刚刚在 Bash、Dash、Ash 和 ZSH 下进行了测试,一切顺利。

【讨论】:

  • charexists "$testchar" $* -- 如果没有引用 $* -- 如果您的参数列表包含 * -- 将表现不佳 -- 除非您想要扩展为当前目录中的文件名列表。
  • 确实!已修复,谢谢!
【解决方案2】:

以下是我的 bash 特定解决方案:

#!/bin/bash
fun()
{
  not_allowed=' ' # Charater which is not allowed
  [[ "$1" =~ $not_allowed ]] && echo "Character which is not allowed found"
}

fun "TestWithoutSpace"
fun "Test with space"

【讨论】:

  • 使用我的解决方案中找到的测试用例,您提出的解决方案仅打印 34,因此前 2 个测试失败。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 2020-11-03
  • 2017-12-29
  • 2012-04-21
相关资源
最近更新 更多