Richard Rublev Richard Rublev - 3 months ago 15
Bash Question

Bash literal match

My script

#!/bin/bash

shopt -s extglob
for i in *.dat;
do
if [[ "$i" == *(_TEx) ]];then
file1=$i
fi
done

echo file1="$file1"


I have tested the script with
http://www.shellcheck.net/

$ shellcheck myscript
No issues detected!


Files

262_V01_C00_R000_TEx_BL_2048H.dat
262_V01_C01_R000_TEy_BL_2048H.dat
262_V01_C02_R000_THx_BL_2048H.dat
262_V01_C03_R000_THy_BL_2048H.dat


But

milenko@milenko-HP-Compaq-6830s:~/procmt$ bash a8.sh
file1=


Why?

Answer

The minimal modification to your attempt to make it work would be this:

    if [[ "$i" == *_TEx* ]]; then

i.e. remove the parentheses and add the missing * at the end of the pattern. There's no need to set the extglob shell option, as you don't need to use any of its features.

However, you might as well change the glob that your are looping over to this:

for i in *_TEx*.dat;

and avoid the if entirely.

Better yet, you could just print the matches directly:

shopt -s nullglob
printf '%s\n' *_TEx*.dat # print all files matching the pattern

nullglob is useful here as it will result in no output when no files match the pattern.

Comments