help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Should read -a respect quoted strings?


From: Greg Wooledge
Subject: Re: Should read -a respect quoted strings?
Date: Fri, 17 Oct 2025 14:16:50 -0400
User-agent: Mutt/1.10.1 (2018-07-13)

On Fri, Oct 17, 2025 at 17:11:49 +0000, Gregory Bartholomew wrote:
> Just in case someone else comes across this thread while trying to find how
> to read user input with readline support and get the result into an array
> while respecting quotes, below is what I found to work.
> 
> #!/usr/bin/bash
> 
> shopt -s lastpipe
> 
> function handler {
>   printf '%s\n' "$@"
> }
> 
> read -e -p 'parameters: ' input
> printf -- "$input" | xargs -r -n 1 | readarray -t args
> [[ ${#args[@]} -gt 0 ]] && handler "${args[@]}"

You must not have tested it thoroughly.  xargs is notoriously poor at
handling unexpected input.  In this case, mismatched quotes will break it:

hobbit:~$ input="Can't work"
hobbit:~$ printf -- "$input" | xargs -r -n 1 | { readarray -t args; declare -p 
args; }
xargs: unmatched single quote; by default quotes are special to xargs unless 
you use the -0 option
declare -a args=()

Your subsequent correction doesn't change this:

hobbit:~$ printf -- "$input" | xargs -r -n 1 printf -- '%s\n' | { readarray -t 
args; declare -p args; }
xargs: unmatched single quote; by default quotes are special to xargs unless 
you use the -0 option
declare -a args=()

I very much doubt you're going to find a solution that you'll be happy
with.  You'll need to define how you want to handle all the corner cases
(no quotes, matched quotes, mismatched quotes, nested quotes, nested
mixed mismatched/matched quotes, ...), and then probably write your own
scanner that processes the input line character by character, assigning
"words" (however you end up defining them) into array elements.

There's no standard POSIX tool I'm aware of that handles this gracefully.
xargs "works" for the simple, well-formed input cases, but nothing else.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]