如何在 sh 字符串比较中使用 *

how to use * in sh string comparison

sh中如何正确使用*?我试着用谷歌搜索但找不到任何东西。以下回声。这是为什么?

file="test test"

if [ "$file" != "te"* ]

then

   echo true

else

   echo false

fi

我用谷歌搜索了一下,找到了一个很好的 bash 脚本资源: Advanced Bash-Scripting Guide

有一个片段可以回答您的问题:

[[ $a == z* ]]   # True if $a starts with an "z" (pattern matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).

[ $a == z* ]     # File globbing and word splitting take place.
[ "$a" == "z*" ] # True if $a is equal to z* (literal matching).

所以在你的情况下,条件应该是:

if [[ file != te* ]]

为避免所有潜在问题,在使用 POSIX shell 时,您应该考虑使用旧的 expr 正则表达式或匹配表达式。您的选择是:

#!/bin/sh

file="test test"

if [ $(expr "$file" : "te.*") -gt 0 ]
then
    echo true
else
    echo false
fi

if [ $(expr substr "$file" 1 2) = "te" ]
then
    echo true
else
    echo false
fi

不优雅,但它们是 shell 的合适工具。每个的简短解释和每个的 expr 语法是:

string : regularExp          : returns the length of string if both sides match, 
                               returns 0 otherwise
match string regularExp      : same as the previous one
substr string start length   : returns the substring of string starting from 
                               start and consisting of length characters