Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do ANSI C quoting of an existing bash variable?

Tags:

bash

sed

quoting

I have looked at this question, but it does not cover my use case.

Suppose I have the variable foo which holds the four-character literal \x60.

I want to perform ANSI C Quoting on the contents of this variable and store it into another variable bar.

I tried the following, but none of them achieved the desired effect.

bar=$'$foo'   
echo $bar     
bar=$"$foo"     
echo $bar       

Output:

$foo
\x61

Desired output (actual value of \x61):

a

How might I achieve this in the general case, including non-printable characters? Note that in this case a was used just as an example to make it easier to test whether the method worked.

like image 572
merlin2011 Avatar asked Apr 23 '14 05:04

merlin2011


People also ask

How do I quote a variable in bash?

Normally, $ symbol is used in bash to represent any defined variable. But if you use escape in front of $ symbol then the meaning of $ will be ignored and it will print the variable name instead of the value. Run the following commands to show the effects of escape character (\).

What is $$ variable in bash?

$$ is a Bash internal variable that contains the Process ID (PID) of the shell running your script. Sometimes the $$ variable gets confused with the variable $BASHPID that contains the PID of the current Bash shell.


1 Answers

By far the simplest solution, if you are using bash:

printf %b "$foo"

Or, to save it in another variable name bar:

printf -v bar %b "$foo"

From help printf:

In addition to the standard format specifications described in printf(1) and printf(3), printf interprets:

 %b        expand backslash escape sequences in the corresponding argument
 %q        quote the argument in a way that can be reused as shell input
 %(fmt)T output the date-time string resulting from using FMT as a format
         string for strftime(3)

There are edge cases, though:

\c terminates output, backslashes in \', \", and \? are not removed, and octal escapes beginning with \0 may contain up to four digits

like image 133
rici Avatar answered Oct 04 '22 12:10

rici