我在Bash中有一个字符串:

string="My string"

如何测试它是否包含另一个字符串?

if [ $string ?? 'foo' ]; then
  echo "It's there!"
fi

哪里是我不认识的接线员。我使用echo和grep吗?

if echo "$string" | grep 'foo'; then
  echo "It's there!"
fi

这看起来有点笨拙。


当前回答

公认的答案是正确的,但很难阅读和理解。对于与搜索相关的问题,应始终使用$needle in a$haystack习语。由于建议的编辑队列已满,我发布了以下内容:

haystack='There are needles here.'
if [[ "$haystack" == *"needle"* ]]; then
    echo "It's there!"
fi

其他回答

grep-q对于这个目的很有用。

同样使用awk:

string="unix-bash 2389"
character="@"
printf '%s' "$string" | awk -vc="$character" '{ if (gsub(c, "")) { print "Found" } else { print "Not Found" } }'

输出:

未找到

string="unix-bash 2389"
character="-"
printf '%s' "$string" | awk -vc="$character" '{ if (gsub(c, "")) { print "Found" } else { print "Not Found" } }'

输出:

建立

原始来源:http://unstableme.blogspot.com/2008/06/bash-search-letter-in-string-awk.html

正如Paul在绩效比较中提到的:

if echo "abcdefg" | grep -q "bcdef"; then
    echo "String contains is true."
else
    echo "String contains is not true."
fi

这是符合POSIX的,就像Marcus提供的答案中的“case“$string”一样,但它比case语句答案更容易阅读。还要注意,这将比使用case语句慢得多。正如保罗所指出的,不要在循环中使用它。

您应该记住,shell脚本不是一种语言,而是一组命令。你本能地认为这种“语言”要求你在if后面加一个[或一个[[。这两个命令都只是返回一个表示成功或失败的退出状态的命令(就像其他所有命令一样)。出于这个原因,我会使用grep,而不是[命令。

只要做到:

if grep -q foo <<<"$string"; then
    echo "It's there"
fi

既然您正在考虑如果测试它后面的命令的退出状态(用分号完成),为什么不重新考虑您正在测试的字符串的源代码?

## Instead of this
filetype="$(file -b "$1")"
if grep -q "tar archive" <<<"$filetype"; then
#...

## Simply do this
if file -b "$1" | grep -q "tar archive"; then
#...

-q选项使grep不输出任何内容,因为我们只需要返回代码使shell展开下一个单词,并将其用作命令的输入,这是<<here文档的一行版本(我不确定这是标准还是巴什主义)。

此堆栈溢出答案是唯一一个陷阱空格和破折号字符的答案:

# For null cmd arguments checking   
to_check=' -t'
space_n_dash_chars=' -'
[[ $to_check == *"$space_n_dash_chars"* ]] && echo found

我的.bash_profile文件以及我如何使用grep:

如果PATH环境变量包含我的两个bin目录,请不要追加它们,

# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

U=~/.local.bin:~/bin

if ! echo "$PATH" | grep -q "home"; then
    export PATH=$PATH:${U}
fi