2

Just an illustration:

first

cd /usr/lib

and run

for x in $(ls);do if [ "$x" == "*.a" ];then echo $x;fi;done

What I want to do is to select files with extension .a and print them. I know there are much simpler way of doing this, but that is not my intention here.

The problem is that the command above doesn't work. I don't know why. I learn this from this post

I also tried

[ "$x" == *.a ]    bash: [: too many arguments
[ $x = "*.a" ]    shows nothing
[ $x = *.a ]    bash: [: too many arguments

I know [[ $x == *.a ]] works, but I want to know what is the correct way to write [ test in this case?

user15964
  • 713

2 Answers2

4
for x in ./*; do
   case $x in
      *".a" ) echo "$x";;
   esac
done

The [ construct is not exactly suited for this. But if you insist, we may do it like as follows:

[ '.a'  =  ".${x##*.}" ]

Explanation

Say $x contains: my.file.testing.a Then ${x##*.} will , starting from the left, strip away as much as it can till the last . it manages to see in $x. IOW, we end up dropping everything and bringing the extension viz, a to the fore. So now we have the extension we just computed to compare against what we think it better be(.a) for success.

1

The answer you linked to in your question uses bash's (double-bracket) extended test syntax, whereas you are trying to use the POSIX single-bracket test operator. The difference is that in the double-bracket test, the right hand side of an == is treated as a pattern rather than being subject to word splitting or glob expansion. So whereas [ $f == *.a ] results in the [: too many arguments error, you may do

for f in *; do if [[ $f == *.a ]]; then echo "$f"; fi; done

or (more compactly)

for f in *; do [[ $f == *.a ]] && echo "$f"; done

Alternatively, since you appear to be using bash, you could use the =~ regular expression operator e.g.

for f in *; do if [[ $f =~ \.a$ ]]; then echo "$f"; fi; done

or (more compactly)

for f in *; do [[ $f =~ \.a$ ]] && echo "$f"; done

although it's overkill in this case.

steeldriver
  • 81,074
  • Oh, my god. After reading that linked answer again. I found I misinterpreted the author. Thank you for answering, expecially for mentioning the overkill =~ syntax – user15964 Mar 10 '17 at 01:11