The behavior is correct and "as expected."
for file in $InputDir'*' means assign "/home/XXX/*" to $file (note the quotation marks). Since you indicated an asterisk, it will not be executed at this time. When the shell sees echo $file , it first expands the variables, and then extends glob. So after the first step he sees
echo /home/XXX/*
and after glob extension he sees:
echo /home/XXX/fileA /home/XXX/fileB
Only now will he execute the command.
In the second case, the template /home/XXX/* expanded before execution of for and, therefore, each file in the directory is assigned to file , and then the loop body is executed.
This will work:
for file in "$InputDir"*
but it is fragile; it will not work, for example, when you forget to add / to the end of the $InputDir variable.
for file in "$InputDir"/*
slightly better (Unix will ignore double slashes in the path), but this can cause problems when $InputDir not installed or empty: you will unexpectedly list files in the / (root) folder. This can happen, for example, due to a typo:
inputDir=... for file in "$InputDir"/*
Unix Case :-)
To help you understand this code, use set -x ("enable tracing") in the line before the code you want to debug.
source share