$ str="a'\"b"
$ declare -p str
declare -- str="a'\"b" # see " was escaped, possibly other chars will too
$ astr=("$str" "c")
$ declare -p astr
declare -ax astr='([0]="a'\''\"b" [1]="c")'

so, is there some way to do something like declare -p astr[0] and retrieve something like this: declare -- astr[0]="a'\"b" ?

I could use sed or something else, but I would like to know if bash allow accessing astr[n] thru declare -p in some way I couldn't guess yet?


If you are just looking for a way of displaying the data with escaped special characters, then the %q format string of printf in bash would do that for you:

printf '%q\n' "${astr[0]}"

To replicate the declare -p-like output that you suggest:

printf 'declare -- astr[0]="%q"\n' "${astr[0]}"

This is from the bash manual, regarding the %q format string of printf:


causes printf to output the corresponding argument in a format that can be reused as shell input.

| improve this answer | |
  • it is a lot simpler than using sed and does the same thing I was looking for, thx! – Aquarius Power Jan 12 '19 at 22:41

With bash v4.4 you can use the @A parameter expansion operator to get similar results, but not effectively for a single array element:


The expansion is a string in the form of an assignment statement or declare command that, if evaluated, will recreate parameter with its attributes and value.

$ str="a'\"b"
$ astr=("$str" "c")
$ echo ${astr[0]@A}
declare -a astr='a'\''"b'
$ echo ${astr[@]@A}
declare -a astr=([0]="a'\"b" [1]="c")

Or similar to the %q printf format you can use the @Q operator:

$ echo ${astr[0]@Q}
$ echo "declare -- astr[0]=${astr[0]@Q}"
declare -- astr[0]='a'\''"b'
| improve this answer | |
  • 1
    a new feature, interesting! mine is v4.3.48, I am almost installing 18.04 (16.04 here), I will check then :) – Aquarius Power Jan 12 '19 at 22:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.