Richard Rublev Richard Rublev - 3 months ago 12
Bash Question

Logical OR in my shell script

My script:

#!/bin/bash

for file in *.ats;
do
if [[ ("${file}" = THx) || ("${file}" = THy)]]
then cp $file /home/milenko/procmt
fi
done


Files in directory

262_V01_C00_R000_TEx_BL_128H.ats
262_V01_C01_R000_TEy_BL_128H.ats
262_V01_C02_R000_THx_BL_128H.ats
262_V01_C03_R000_THy_BL_128H.ats


What I wanted is to copy the files that contain THx or THy,but files are not copied.
Why?

Answer

What about using extglob for extended globbing? This way you can use the for itself to get the required extensions:

shopt -s extglob
for file in *TH?(x|y)*.ats; do
   # do things with "$file" ...
done

*TH?(x|y)*.ats expands to those files containing <something> + TH + either x or y + <something> + .ats


Your script fails because you have a typo in it:

if [[ ("${file}" = THx) || ("${file}" = THy)]]
#                                          ^
#                              missing space

This is fine:

$ d="hi"
$ [[ ($d == hi) || ($d == ha) ]] && echo "yes"
yes

Although the parentheses are superfluous:

$ [[ $d == hi || $d == ha ]] && echo "yes"
yes