0

Given a variable VAR, that may contain an empty string, is it possible to make bash always interpret both

ls $VAR
ls "$VAR"

as "command that is given one argument"?


For bash, the IFS variable allows determining how the unquoted variable expansion in the first command is interpreted, defaulting to "Split the string at newlines, tabs and spaces, and treat each one as separate argument."

Things can be made a bit more convenient by settings IFS=''. But even then, if $VAR expands to am empty string, it will not be treated as the empty string but as absence of an argument.

This behavior actually makes sense for other values of IFS: By default unquoted expansion is treated as "list of whitespace-separated tokens", with the empty string being the empty list.

But is there a feature, to make $VAR and "$VAR" truely equivalent, at least for IFS=''?

kdb
  • 4,098
  • 26
  • 49
  • 3
    What about using `${VAR:-""}`? – choroba Aug 29 '19 at 19:02
  • @choroba It is more about about avoiding the possibility of bugs resulting from unquoted expansions. `${VAR:-""}` with `IFS=''` would be just a rather obscure way of writing `"$VAR"`. – kdb Aug 29 '19 at 20:28
  • 1
    You can try to make your own shell, only parsing the variables (adding quotes) and calling the original bash afterwards. This will introduce new bugs for places where the quotes are missing on purpose. – Walter A Aug 29 '19 at 20:52
  • @WalterA The purpose is mostly for my own scripts and interactive use, so it won't introduce bugs. However, it would be severe overkill to rewrite bash for this; At that point writing `"$VAR"` everywhere would be a rather minor compromise. – kdb Aug 29 '19 at 20:57
  • I once wrote a script for changing all `$VAR` into `${VAR}`. You might want to edit your own scripts and change them into `"${var}"` (lowercase, quotes). Then run a diff between your original code and changed one for checking unwanted conversion results. – Walter A Aug 29 '19 at 21:17

0 Answers0