Quantcast
Channel: User Kamil Maciorowski - Super User
Viewing all articles
Browse latest Browse all 837

Answer by Kamil Maciorowski for Bash provide comma-separated list in multiple lines

$
0
0

Store the values without separators in an array. Use the fact that "${array[*]}" expands to a single word that contains all the members of the array concatenated, with the first character of $IFS in between.

For what you want to do, you need IFS=,.

The altered IFS may affect commands later in the script, including the one that gets the argument in question (./file-selector in your case). To avoid this, use the altered IFS only to rewrite the array to a non-array variable; next restore the old value of IFS and only then run actual commands.

Saving and restoring IFS has its quirk: empty is not equivalent to unset (although "$IFS" expands to an empty string in both cases). Still Bash (at least Bash 5.2.15 I tested) sets IFS to <space><tab><newline> when it starts interpreting a script, so the initial IFS in your script is certainly neither empty nor unset. This means it's safe to store and restore it. Hardcoded IFS=$' \t\n' to restore the default value would also work.

Proof of concept:

#!/bin/basholdIFS="$IFS"excludes=(            a/b/c/d/e/f1            a/b/c/d/e/f2            a/b/c/d/e/f3            a/b/c/d/e/f4            a/b/c/d/e/f5            a/b/c/d/e/f6         )IFS=,exc="${excludes[*]}"IFS="$oldIFS"printf '<%s>\n' ./file-selector -exclude="$exc"

The output is:

<./file-selector><-exclude=a/b/c/d/e/f1,a/b/c/d/e/f2,a/b/c/d/e/f3,a/b/c/d/e/f4,a/b/c/d/e/f5,a/b/c/d/e/f6>

which means the argument was exactly as you wanted.

The whole snippet is not very readable (especially for someone who does not know the trick), but the list of paths is extremely clear (and also descriptive, due to the array having a meaningful name).

Note a path/with spaces or so needs to be quoted or escaped when you store it in an array. Example:

excludes=(            a/b/c/d/e/f1'path/with spaces or so'            another/path\ with\ spaces         )

Viewing all articles
Browse latest Browse all 837

Trending Articles