1

I have a .sh file in which I have written the following function. The command that calls this function will have the arguments- file1.war, file2.war ... fileN.war and other arguments.

I want to do a certain operation to the .war files and something else for the arguments after it. So I have written a while loop that will run till the arguments are .war files, and when an argument is encountered without .war extention, it will exit the loop and run the code below it for the rest of the arguments.

Here is the function in .sh file :

copyWarFiles()
{
downloadFileName=$1
    shift 1
extn=".war"
while [ condition ]
do      
        log "war file $downloadFileName .."
         #some operation..
        downloadFileName=$1
        shift 1
done
#operations for the rest of the arguments...
}

What should I give as condition that will return true if $downloadFileName ends with .war? I tried giving $downloadFileName==*".war" (following the accepted answer in this ) and I also tried this :

`test "${downloadFileName#*$extn}" != "$downloadFileName"` 

(following the accepted answer here) where extn is another variable I declared and assigned to .war.

But in both the cases, I see that it never enters the while loop. I think I have gone wrong with the syntax or something. Thank you for your help in advance.

Community
  • 1
  • 1
Ridhima
  • 308
  • 1
  • 3
  • 14

2 Answers2

2

What should I give as condition that will return true if $downloadFileName ends with ".war"? I tried giving $downloadFileName==*".war" […]

Bash, unlike typical programming languages, doesn't recognize == as a special operator; it's just yet another argument to the [ command. So you need to set it off with spaces.

Also, the [ command doesn't support having a pattern on the right-hand-side of ==; you need to use the special [[ ... ]] notation.

So:

while [[ $downloadFileName == *".war" ]]

Note, though, that the double-quotes around .war don't actually have any effect: none of the characters in .war are special characters that need to be quoted. Conversely, it's a best practice to always put variable expansions in double-quotes, in case the variables contain special characters. ([[ actually negates most of the problematic behaviors, but it's just a good habit to be in.)

So:

while [[ "$downloadFileName" == *.war ]]
ruakh
  • 175,680
  • 26
  • 273
  • 307
1

Why not just:

check=`echo $downloadFile | grep '\.war'`
if [ -n "$check" ]; then
    echo $downloadFile ends in .war
fi
sureshvv
  • 4,234
  • 1
  • 26
  • 32