Question

Word splitting bash parameter on whitespace respecting and retaining quotes

Given the bash parameter

foo='ab   "cd" "e f"  x="1 2" '

I wish to produce an array equivalent to

foo_transformed=( ab '"cd"' '"e f"' 'x="1 2"' )

in a portable way, meaning using either bash (v3+) builtins or programs available to most operating systems (Linux, Unix, Cygwin) by default. Simplicity and safety, given (almost) arbitrary input string, are desirable.

You may assume the input does not contain single quotes ' or backslashes \, but may contain an arbitrary number of whitespace characters, both where I wish them to delimit the string and where they do not (when inside double quotes).

If we try:

foo_transformed=( $foo )

then the internal quotes of foo are not respected (for k in "${foo_transformed[@]}"; do echo "- $k"; done):

- ab
- "cd"
- "e
- f"
- x="1
- 2"

If we try:

eval foo_transformed=( $foo )

then the quotes are lost:

- ab
- cd
- e f
- x=1 2
 4  154  4
1 Jan 1970

Solution

 2
re=$'[ \t]*(([^ \t"]+|"[^"]*")+)'
s=$foo
foo_transformed=()

while [[ $s =~ $re ]]; do
    foo_transformed+=("${BASH_REMATCH[1]}")
    s=${s#"${BASH_REMATCH[0]}"}
done

The regex allows foo to contains embedded newlines between double-quotes. To correctly handle other newlines, replace both instances of \t with \t\n or perhaps [:space:].

(Bash regex doesn't accept \t so I use $'...\t...' syntax to convert into literal tabs/newlines.)


As noted in comments, that will hang on malformed input.

To accept malformed input, this modified regex could be used:

re=$'[ \t]*(([^ \t"]+|"[^"]*("|$))+)'

Alternatively, a pre-check could be done:

malformed='^([^"]+|"[^"]*")*"[^"]*$'
if [[ $foo =~ $malformed ]]; then
    : ...
fi
2024-07-15
jhnc

Solution

 2

This might be what you want:

$ cat tst.sh
#!/usr/bin/env bash

foo='   ab   "cd"
"e f"  '\'' x="1 2"
   z="a b"7"c
 d"8   $HOME
          `date`  *  $(date)   '

fpat='(^[[:space:]]*)([^[:space:]]+|([^[:space:]"]*"([^"]|"")*"[^[:space:]"]*)+)'

foo_transformed=()
while [[ "$foo" =~ $fpat ]]; do
    foo_transformed+=( "${BASH_REMATCH[2]}" )
    foo="${foo:${#BASH_REMATCH[0]}}"
done

declare -p foo_transformed

$ ./tst.sh
declare -a foo_transformed=([0]="ab" [1]="\"cd\"" [2]="\"e f\"" [3]="'" [4]="x=\"1 2\"" [5]=$'z="a b"7"c\n d"8' [6]="\$HOME" [7]="\`date\`" [8]="*" [9]="\$(date)")

I gave foo some extra values including globbing chars, a single quote, potential variable references, old and new style command injections, newlines inside and outside of quoted strings, and strings containing multiple quoted substrings so it could test the script more fully.

The use of the fpat regexp above is inspired by GNU awk's FPAT which is used to identify fields in input, see for example how it's used in CSVs at What's the most robust way to efficiently parse CSV using awk?. It matches:

  • (^[[:space:]]*) - an optional leading sequence of spaces (which are discarded) followed by (...) which matches the string we actually want to capture:
  • [^[:space:]]+ - a series of non-spaces
  • | - or
  • ([^[:space:]"]*"([^"]|"")*"[^[:space:]"]*)+ - a repeated string of double quoted substrings containing any chars, or no chars, optionally surrounded by substrings that don't contain spaces or double quotes.
2024-07-15
Ed Morton

Solution

 1

You could use a string replacement within a declare statement that does exactly what you want in one go:

#!/usr/bin/env bash

# Init
foo='ab   "cd" "e f"  x="1 2" * $(date) `date` $[1+1] $((1+1)) ((1+1)) foo=''"''$HOME''" bar="a '\'' b"'

# If the patsub_replacement shell option is enabled using shopt,
# any unquoted instances of & in string are replaced with the
# matching portion of pattern.
shopt -s patsub_replacement

# Escape arithmetic variables, commands and glob expansions
foo_escaped=${foo//[()\*\?\\\$\`\']/\\&}

# Escape and preserve double-quotes as string delimiters
foo_escaped=${foo_escaped//\"/\"\\\"}

# Transform
declare -a foo_transformed="($foo_escaped)"

# Debug declaration
declare -p foo_transformed

# Debug print
printf %s\\n "${foo_transformed[@]}"

Detailed explanation:

  • ${foo//\"/\"\\\"} replaces each double-quote " in foo by "\", so it remains quoted while containing the quote itself to be retained.

  • declare -a foo_transformed="(${foo//\"/\"\\\"})", uses the transformed string within an array declaration declare -a variable="(string)".

EDIT

Added escape of all expansions

2024-07-15
Léa Gris