Shell脚本:测试一个字符串是否包含一个字符(包括像'*'和'\'这样的字符)[重复]

这个问题在这里已有答案:

在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解释器,因为并非所有这些容器都必须安装它 .

回答(2)

3 years ago

这是我提出的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下测试过,一切顺利 .

3 years ago

以下是我的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"