In bourne shell syntax, an ASCII CR (decimal 13, hex 0x0D or
'\r'
in C syntax) is written as
$'\r'
. This works in all major bourne-compatible shells, including zsh, bash and FreeBSD’s /bin/sh.
If a shell variable VAR contains characters like ASCII CR, you must put them in double quotes in order to expand them properly, like
"$VAR"
.
The following shell script demonstrates how it can be done. It uses two different methods to set two variables to ASCII CR, the first uses
awk(1), the second uses shell syntax. The result should be the same.
Code:
#!/bin/sh -
VAR1=$(awk 'BEGIN {printf "%c", 13}')
VAR2=$'\r'
echo -n "$VAR1" | hd
echo -n "$VAR2" | hd
if [ "$VAR1" = "$VAR2" ]; then
echo equal
else
echo different
fi
It produces the following output:
Code:
00000000 0d |.|
00000001
00000000 0d |.|
00000001
equal
If it doesn’t work for you, then your variable contains something else. You can check with
hd(1), as others have already suggested.
By the way, there are many more ways to produce ASCII CR in shell scripts. Here are more examples:
Code:
VAR=$(echo -e '\r')
VAR=$(echo x | tr x '\r')
VAR=$(python -c 'print(chr(13))')