0

I am using this code to download and unzip data in bash script file

    for dump in $dumps; do
        echo "Downloading $dump into $download_folder"
        wget -c -P "$download_folder" "$geonames_general_data_repo/$dump"
        if [ ${dump: -4} == ".zip" ]; then
            echo "Unzipping $dump into $data_dir"
            unzip "$download_folder/$dump" -d $data_dir
        else
            if [ ${dump: -4} == ".txt" ]; then
                mv "$download_folder/$dump" $data_dir
            fi
        fi
    done

but I got this error :

importer.sh: Bad substitution 

for this line : if [ ${dump: -4} == ".zip" ]

I am using Ubunto 18.04 with latest updates

Ata
  • 12,126
  • 19
  • 63
  • 97
  • Sure it's really running with bash, not `sh`? Ubuntu's `/bin/sh` is dash, not bash. – Charles Duffy Jul 13 '19 at 18:23
  • BTW, `"${dump: -4}"` -- with the quotes -- is going to behave less badly when the value expands to anything other than exactly a single word. And it isn't safe to use `==` as a string comparison operator; POSIX only specifies `=`. – Charles Duffy Jul 13 '19 at 18:24
  • ...anyhow, when you run `sh yourscript`, that script isn't run with the full bash language available, even if your `/bin/sh` *is* bash. And on Ubuntu, it isn't, so you *really* don't get anything other than the baseline POSIX spec. – Charles Duffy Jul 13 '19 at 18:25
  • Similarly, you need quotes around `"$data_dir"` every time you expand it, to ensure that it expands to exactly one shell word. And `for dump in $dumps` implies that you're using a string called `dumps` as if it were an array. That's a really bad idea -- use a real shell array, and array syntax, instead (though that'll force you to a shell -- like bash -- that actually supports arrays). – Charles Duffy Jul 13 '19 at 18:26
  • ...wait, do you want `${dump: -4}` to expand to the last four characters of `dump`? That's not what it does at all, except in very new shell releases. Switch to bash, and use `[[ $dump = *.zip ]]`; or, in any POSIX shell, use a `case` statement, as in, `case $dump in *.zip) echo "yes it ends in zip";; *) echo "no it does not end in zip";; esac` – Charles Duffy Jul 13 '19 at 18:27
  • You can use `if [ "${dump%.zip}" != "$dump" ]` as a portable extension test. The way it works is that the `%.zip` part removes ".zip" from the end of the filename *if it matches that*, and if it does match the result will be different from the unmodified filename. This form of variable expansion will work in any POSIX-compatible shell. – Gordon Davisson Jul 13 '19 at 18:58

0 Answers0