1

I would like to stringify a given command, given as an array.

This would be useful to for example put a command inside a bash -c.

For example :

cmd=(
  "printf '%s\n'"
  "foo bar"
  "baz bang"
)

stringified="$(transform "${cmd[@]}")"

So that : "${cmd[@]}" and bash -c "$stringified" would give the exact same output for any cmd array.

In my example, that would be :

$ "${cmd[@]}"
foo bar
baz bang

The value of stringified="printf \"%s\n\" \"foo bar\" \"baz bang\"" works for my case, but I wish to have a transform function that would properly escape those arguments for me.

Preferably, I would prefer a bash solution, or if that is not the case, with tools that are usually already installed on a linux distribution (printf, echo).

1

I found a good solution for this (I think it would work for any input array), it uses the printf "%q" feature.

You can just write :

cmd=(
  "printf '%s\n'"
  "foo bar"
  "baz bang"
)

stringified="$(printf "%q " "${cmd[@]}")"

This gives :

printf\ \'%s\\n\' foo\ bar baz\ bang

Explanation

The printf "%q" command escapes characters to be used in shell :

%q ARGUMENT is printed in a format that can be reused as shell input, escaping non-printable characters with the proposed POSIX $'' syntax.

Source : man printf

By using "%q ", all elements in the array are printed and correctly escaped, and since there is a space after the %q, all elements will be delimited by a space.

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.