Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command for beautiful quoting

Tags:

bash

Sometimes I need to quote an entire command line for future evaluation. Usually I do that with:

printf "%q " "$@"

That's short and sweet but the output look awful. Most of the time this doesn't matter but in occasions I want to show it to the user. For example, in a history of executed commands menu that allows for re-execution of entries. That being the case, I would like to quote in a more readable form (closer to what the user itself would have done if he were in charge of quoting). So this:

search 'Wordreference (eng->spa)' utter

would be preferable to this:

search Wordreference\ \(eng-\>spa\) utter

In order to get the first quoted form I could iterate "$@" and do something like what follows for each argument:

[[ $arg == *\ * ]] && arg="'"${arg//\'/\'\\\'\'}"'"

This is not difficult at all but it involves a loop, a conditional string transformation and concatenation of the result of each iteration.

I wonder if there is a more "batteries included" command to do this kind of transformation out of the box.

like image 866
memeplex Avatar asked Jan 16 '14 16:01

memeplex


1 Answers

In the same way you use eval to later execute the string, you can use eval to print it:

eval "echo $yourstring"

This will remove the shell escapes but keep your variable intact.

like image 196
jordanm Avatar answered Oct 12 '22 23:10

jordanm