0

For a college assignment I was given a part of the sample files used an if statement to check if a file existed and I found the outcome of this if statement changed when the file name was wrapped in double quotes vs when it was just the file name used and can't find out why.

for elem in "$@ ; do if [ ! -e $elem ] ; then echo 1st $$ > $elem else echo next $$ >> $elem fi done When there aren't double quotes around $elem the if statement works correctly and appends the argument with 1st $$ if it doesn't already exist or next $$ if it does exist. When the double quotes are added (which is how the file appears in the sample from my professor), it always writes 1st $$ regardless of whether the file exists or not but can't understand why this happens.

  • Not specific to `[`; it's the same rules that are _always_ true. Run your code through http://shellcheck.net/ and follow the links in the warnings. – Charles Duffy Dec 01 '22 at 19:18
  • BTW, running `bash -x yourscript` is a very good place to start to understand how execution differs. – Charles Duffy Dec 01 '22 at 19:19
  • ...there's not enough information in the question itself to say with certainty _why_ you get behavior you consider more correct when leaving out the quotes, but my best guess is that members of `"$@"` are glob sequences that when run expand to a single filename. Expansion in quotes means no globbing happens. (However, expansion _without_ quotes means globbing _does_ happen, which is likely to lead to incorrect/unwanted behavior whenever any of your glob expressions expand to more than one name, so just leaving the quotes off is a Very Bad Idea). – Charles Duffy Dec 01 '22 at 19:20
  • ...all that said, to give you an answer that goes into more detail about your specific code, we'd need a [mre] -- something we can run ourselves _without changes_ to see the exact same behavior. That means, in this case, specifying your data so when we run it there's the same `"$@"` in use. – Charles Duffy Dec 01 '22 at 19:22

0 Answers0