1

Using glob for looping through files in a folder causes an error when the folder is empty. When it is empty, I would expect the loop not to occur (0 elements), but it does enter the loop and forwards the "unresolved glob string", which is very surprising (at least for me).

The sh file:

#!/usr/bin/env bash
set -e 
set -x 
update_jar_version_in_all_deployment_files() {

  for file in "deployment/"*".json"; do
    echo "parsing file $file"
    tmp=$(mktemp)
    jq --arg jar "$JAR" '.libraries[].jar=$jar' "$file" > "$tmp" && mv "$tmp" "$file"
  done
 
 # why does it reach the echo and print foo?
 echo foo
 exit
}

And get this printed:

+ for file in 'deployment/*.json'
+ echo 'parsing file deployment/*.json'
parsing file deployment/*.json
++ mktemp
+ tmp=/var/folders/ks/y7ym1ylx6qjf0k7_kjz2z9hc0000gn/T/tmp.126PU72C
+ jq --arg jar my-jar.jar '.libraries[].jar=$jar' 'deployment/*.json'
jq: error: Could not open file deployment/*.json: No such file or directory
+ echo foo
foo
+ exit

Why is it passing 'deployment/*.json' literally through the loop? (with JSON files inside the deployment folder, it works normally)

Interesting to say that I wanted to use ls deployment | grep .json, but seems like this is not recommended.

Obviously, I can add a check for empty folders before the loop, but I am wondering why my expectation is not the reality here.

Appreciate any explanation.

YFl
  • 845
  • 7
  • 22

0 Answers0