2

I have defined the below for and if condition in a function. For the first time it runs well. Second time it doesn't gets executed after the for loop, it just writes the echo statement. Why does it behave like this?

for outputFile in $outputFiles
    do
            echo"Output file is $outputFile"

        if [ $outputFile == sampple*.pdf ]; then
            FromFile=$OutputFilePath
            transferFiles
         fi
done
user226759
  • 21
  • 2
  • It doesn't get executed after the first run is coz in the first run, you've transferred all relevant pdf files over, so next time on there aren't any there. HTH. –  Apr 13 '17 at 11:15

1 Answers1

3

To do a test on a string against a file globbing pattern, use case:

case "$outputFile" in
    sampple*.pdf)
        FromFile="$OutputFilePath"
        transferFiles ;;
esac

To do a test on a string against a regular expression in bash or ksh93:

if [[ "$outputFile" =~ ^sampple.*\.pdf$ ]]; then
    FromFile="$OutputFilePath"
    transferFiles
fi

Note the use of [[ ... ]] and =~ rather than [ ... ] and == here.

The [ ... ] construct does not generally support the == operator for comparing strings.

With [[ ... ]] and ==, the right-hand side is taken as a file globbing pattern. So the following should work (in bash or ksh93) as well:

if [[ "$outputFile" == sampple*.pdf ]]; then
   # as before
fi
Kusalananda
  • 333,661
  • Thanks for the help! :) But i have used [...] this in some other functions, there it works fine. I am facing this issue only for a particular function in the script. why does this happen? – user226759 Apr 13 '17 at 10:38
  • We can't tell without seeing the values it loops over. Can you [edit] your question to include the output from bash -x on your script? – tripleee Apr 13 '17 at 10:53
  • @user226759 It's hard to debug a "it doesn't work"-question blindfolded. Please edit your question with the relevant info included. This includes the values that $outputFile may take as well as any error messages. Also note that if your outputFiles variable contains spaces, the shell will split the variable on all of these and set $outputFile to each individual bit in turn. – Kusalananda Apr 13 '17 at 11:02
  • 1
    @user226759 [ works with some operators, but not with pattern matching because you need to quote the pattern. See Single or double brackets. – Gilles 'SO- stop being evil' Apr 14 '17 at 21:06