"revealing" hidden / control "codes" in strings in bash

Python has a very convenient function: repr () , which when applied to a string containing empty characters, prints out the representation of that string, which cannot lead to any human misinterpretation of the actual contents of the string.

eg:

$ python -c "print repr(r'''abcde\rfghi\tjklmn\nopqr\bstuv\fwxyz''')"
'abcde\\rfghi\\tjklmn\\nopqr\\bstuv\\fwxyz'

How can I do the same in bash with printf ?

The perfect tool / trick I'm looking for will literally print

'abcd\refjh\bijk'

for the team

printf "abcd\refjh\bijk" | <something>

The goal of this is to improve a test tool that prints the differences between two lines:

http_response_code=$(curl -s --head http://httpbin.org/ | head -1)  # will put "HTTP/1.1 200 OK\r" in $http_response_code
assert_equal "HTTP/1.1 200 OK" "$http_response_code"
> failed: strings do not match
> expected:   'HTTP/1.1 200 OK'
> actual:     'HTTP/1.1 200 OK'

As you can see, the current implementation allows the user to understand and explain the reasons for the failure.

Idealism Instead, I would like to have the following conclusion:

> failed: strings do not match
> expected:   'HTTP/1.1 200 OK'
> actual:     'HTTP/1.1 200 OK\r'

Current Attempts:

  • printf $'\a\b\e\E\f\n\r\t\v\\\'\"' | cat -A
  • echo $'\a\b\e\E\f\n\r\t\v\\\'\"' | cat -A | sed -r '$!{ N;s/\$\n/\\n/;t sub-yes;:sub-not;P;D;:sub-yes;}'
  • printf $'\a\b\e\E\f\n\r\t\v\\\'\"' | od -c
+4
1

%q :

$ printf '%q' "abcd\refjh\bijk"
abcd\\refjh\\bijk

, ; , '\r' \\r . ,

$ printf '%q' $'\a\b\e\E\f\n\r\t\v\\\'\"'
$'\a\b\E\E\f\n\r\t\v\\\'"'

ANSI, , .

ANSI , , , , .

$ var="My string"
$ printf -v var '%q' "$var"$'\n'   # Add a newline
$ [[ $var =~ \$\'(.*)\\n\' ]] && var="\$'${BASH_REMATCH[1]}'"
$ echo "$var"
+4

Source: https://habr.com/ru/post/1607111/


All Articles