2
$ 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?

2 Answers 2

4

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:

%q

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

1
  • it is a lot simpler than using sed and does the same thing I was looking for, thx! Jan 12, 2019 at 22:41
0

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

A

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}
'a'\''"b'
$ echo "declare -- astr[0]=${astr[0]@Q}"
declare -- astr[0]='a'\''"b'
1
  • 1
    a new feature, interesting! mine is v4.3.48, I am almost installing 18.04 (16.04 here), I will check then :) Jan 12, 2019 at 22:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .