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

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"cn 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.

1

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 tn 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

2

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

9

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật