0

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).

For example if the user passes in the argument '*.c', and I have these files to check it against:

~/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':

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.

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.

10
  • What do you see when you run the script under set -x at the beginning? Commented Feb 27, 2015 at 8:00
  • @Jens Interesting.. if I have a file called test.c it shows that it is checking [[ test.c == \*\.\c ]] Commented Feb 27, 2015 at 8:03
  • @Jens Changing it to if [ "$i" == "$1" ] now shows it testing for [ test.c = '*.c' ] and passing in just *.c as an argument (no single quotes) shows it as [ test.c = *.c ].. but for whatever reason it still is not showing that it is a match. Commented Feb 27, 2015 at 8:08
  • Have you tried [ "$i" =~ "$1" ] ? Commented Feb 27, 2015 at 8:32
  • 1
    Note: If you use double square brackets [[...]] in bash you won't need to put quotes around variables. So [[ $i == $var ]] always works (in contrast to [ "$i" == "$var" ] where quotes are required because otherwise you get errors e.g. if at least one of the variables contain whitespace). Commented Feb 27, 2015 at 8:58

1 Answer 1

1

First declare the glob as a variable, then use the variable in the test. So, declare:

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

The reason for this is to force bash to expand the wildcard before the test.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.