简体   繁体   English

字符串匹配在bash脚本中不起作用

[英]String matching not working in bash script

This is weird.. mainly because it worked last night. 这很奇怪..主要是因为它昨晚有效。 I have a script that is passed in an expression that is supposed to match file names in an array. 我有一个在表达式中传递的脚本,该表达式应该与数组中的文件名匹配。 I'm not allowed to use find however (it is for an assignment). 但是我不允许使用find (这是一项任务)。

For example if the user passes in the argument '*.c' , and I have these files to check it against: 例如,如果用户传入参数'*.c' ,而我有以下文件'*.c'来检查:

~/dir/text1.txt
~/dir/no.c
~/dir/no.sh

I do the comparison in a function like so: 我在这样的函数中进行比较:

process ()
{
   local new_cur=()
   for i in "${files[@]}"; do
       if [[ "$i" == "$1" ]]; then
           new_cur+=("$i")
       fi
   done
}

I then call this in the bash script like this, where arguments[1] is = to '*.c' : 然后,我在bash脚本中这样称呼它,其中arguments[1] = = '*.c'

process "${arguments[1]}"

Inside my process function, I checked and the string *.c is being passed in, and the files are being passed in. However it is not passing the if statement within my function. 在我的process函数内部,我检查了字符串*.c并传入了文件,并且传入了文件。但是,它没有在函数中传递if语句。

Note that this also does not work for even simple strings without wildcards. 请注意,即使没有通配符的简单字符串也无法使用。

Edit: I have also looked up common solutions, and for whatever reason none work. 编辑:我也查找了常见的解决方案,无论出于何种原因都没有用。 Here is what I have tried: 这是我尝试过的:

if [ "$i" == "$1" ]
if [ "$1" == "$i" ]
if [ "$i" = "$1" ]
if [ "$1" = "$i" ]
if [[ "$1" = "$i" ]]
if [[ "$i" = "$1" ]]
if [[ "$1" == "$i" ]]
if [[ "$i" == *"$1"* ]]

So far none of the above have worked. 到目前为止,以上方法均无效。

First declare the glob as a variable, then use the variable in the test. 首先将glob声明为变量,然后在测试中使用该变量。 So, declare: 因此,声明:

var="$1" then [ $i == $var ] 

The reason for this is to force bash to expand the wildcard before the test. 这样做的原因是在测试之前强制bash扩展通配符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM