From b7132c871b01e41de9a6500a5d828801fc61f4b8 Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Fri, 6 Dec 2013 11:38:31 -0500 Subject: bash-arrays: 2013-12-06 update: When it's ok to not quote arrays --- public/bash-arrays.md | 46 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/public/bash-arrays.md b/public/bash-arrays.md index a52be39..aee5ec0 100644 --- a/public/bash-arrays.md +++ b/public/bash-arrays.md @@ -45,8 +45,8 @@ difference between `@` and `*`. @@ -106,8 +106,8 @@ getting it as separate items, and as a whitespace-separated string):

Substitute * for @ to get the subset as a whitespace-separated string instead of separate tokens, as described above.

-

Again, there is no valid reason to not wrap each of these in - double quotes.

+

Again, there is almost no valid reason to not wrap each of + these in double quotes.

@@ -240,3 +240,41 @@ GNU programs, the `--` tells it to not parse any of the options as flags. The `shift` command shifts each entry n spots to the left, using n=1 if no value is specified; and leaving argument 0 alone. + +---- + +2013-12-06 update: When it's okay to not quote arrays +----------------------------------------------------- + +I mentioned that there is "almost no" valid reason to not wrap +`${array[@]}` in double-quotes. Seriously, you probably want to put +it in quotes. In an earlier version, I wrote "no", and in an even +earlier draft I wrote "no reason that I can think of". Well, I just +changed it to "almost no", because I thought of a reason: + +It is okay to not quote it when you are doing field-separator +manipulations. For example: + + # Usage: path_la PATH1 PATH2... + # Description: + # Takes any number of PATH-style values; that is, + # colon-separated lists of directories, and prints a + # newline-separated list of executables found in them. + # Bugs: + # Does not correctly handle programs with a newline in the name, + # as the output is newline-separated. + path_ls() { + local dirs + IFS=: dirs=($@) # The odd-ball time that it needs to be unquoted + find -L "${dirs[@]}" -maxdepth 1 -type f -executable -printf '%f\n' 2>/dev/null | sort -u + } + +The explanation is that no field-separator evaluation is done when you +quote the array. This is almost always what you want—the array is +already field-separated; you don't want that to be re-evaluated, and +possibly changed. However, if you do have character-separated fields +that you want to get at, you do want field-separation to be +re-evaluated. + +But seriously, quote your arrays by default. If they need to be +unquoted, you should think long and hard before doing so. -- cgit v1.1-4-g5e80

Getting an entire array

-

There is no valid reason to not wrap these in double - quotes.

+

There is almost no valid reason to not wrap these in + double quotes.