Search code examples
bashglobls

Linux bash script: using ls with glob and getting output in variable not working


On my CentOS 7 machine, I have a folder which contains 2 files, with names like:

myapp-nightly__v3.0-SNAPSHOT__b59__lite.zip
myapp-nightly__v3.0-SNAPSHOT__b59.zip

These files are erased and generated every night, and the number after the "b" (in the example above, 59), is incremented.

I want to have a bash script file, in which I can get, in a variable, the name of the file that doesn't contain "_lite" in it (in the example above, that would be "myapp-nightly__v3.0-SNAPSHOT__b59.zip")

So, I first tried "ls" with globbing in a terminal, to see how that works:

ls myapp-nightly__v3.0-SNAPSHOT__b+([0-9]).zip

This correctly outputs "myapp-nightly__v3.0-SNAPSHOT__b59.zip".

Then I tried making a simple bash script, that runs the above command, and stores its output in a variable:

#!/bin/bash
MYAPP_KIT_FULL_PATH=$(ls myapp-nightly__v3.0-SNAPSHOT__b+([0-9]).zip)
echo "MYAPP_KIT_FULL_PATH=$MYAPP_KIT_FULL_PATH"

This gives me the following error:

./test.sh: command substitution: line 3: syntax error near unexpected token `('
./test.sh: command substitution: line 3: `ls myapp-nightly__v3.0-SNAPSHOT__b+([0-9]).zip)'

So my question is, how do I correctly execute such a "ls" command in a bash script, and store its output in a variable? Does this not work in bash because of the glob characters?

Extra remarks:

  • I know the error message says "line 3" but I'm pretty sure it refers to line 2 (line 3 just does an echo). Even if I completely erase line 3 from the script (so that the script only has 2 lines), it still gives the error about line 3

Solution

  • You could use find :

    find dir -maxdepth 1 -name 'myapp-nightly__v3.0-SNAPSHOT__b*.zip' -not -name '*lite.zip'
    

    To unzip the target file in your current directory :

    find dir -maxdepth 1 -name 'myapp-nightly__v3.0-SNAPSHOT__b*.zip' -not -name '*lite.zip' -exec unzip {} \;