I have a BASH script problem that I've narrowed down but I can't understand what I'm seeing. I want to get a substring of an array in a succinct way. Here's what I'm seeing in bash, with 'set -x' so that commands are printed as they are executed:
$: read -a colours
+ read -a colours
blue green red yellow pink purple
$: echo ${colours[@]}
+ echo blue green red yellow pink purple
blue green red yellow pink purple
$: expr substr "${colours[@]}" 16 6
+ expr substr blue green red yellow pink purple 16 6
expr: syntax error: unexpected argument ‘yellow’
$: expr substr \"${colours[@]}\" 16 6
+ expr substr '"blue' green red yellow pink 'purple"' 16 6
expr: syntax error: unexpected argument ‘yellow’
The last attempt at the expr substr
command returned odd quoting for the array elements, so where did that come from? Help me understand what expr substr
is doing here or is this a bug?
EDIT: I've listed below some desired behaviour on a flat quoted string, but why can't I quote an array in the same way?
$: all_colours=${colours[@]}
+ all_colours='blue green red yellow pink purple'
$: expr substr $all_colours 16 6
+ expr substr blue green red yellow pink purple 16 6
expr: syntax error: unexpected argument ‘yellow’
$: expr substr "$all_colours" 16 6
+ expr substr 'blue green red yellow pink purple' 16 6
yellow
"${colours[*]:16:6}"
? If I understand you, you are trying to expand the bash array into a string, and then get its substring. I would do it on this way. I am 99% sure that"${arrayvariable[*]}"
will expand it into a string. I am not sure, how can this be useful.expr
is a program used in ancient shell code to do math. This syntax has been obsolete for a few decades. In Posix shells like bash, use$(( expression ))
. In bash, ksh, mksh, pdksh or zsh, you can also use(( expression ))
\"${colours[@]}\"
. Theset -x
output is shell-quoted to make it unambiguous, it just shows those arguments single-quoted. That'"blue'
is the same as\"blue
. (I would fully expect that when it gets toset -x
printing, the shell doesn't even remember what quotes the initial command line used.)