Bash read of a newline, printf reports character 0

bashnewlinesreadshell-script

I use bash printf function to print ASCII codes of characters in an input file, but for some reason printf outputs ascii code 0 for LF characters, instead of 10. Any ideas why?

while IFS= read -r -n1 c
do
ch=$(LC_CTYPE=C printf "%d\n" "'$c") # convert to integer
echo "ch=$ch"
done < input_file_name

To be honest, I am not even sure if this is a problem with printf or it is the read function, which supplies the wrong value of LF… Are there other ways how to convert characters to ASCII using bash commands?

Best Answer

first your printf function works perfectly

$ export c=" "
$ LC_CTYPE=C printf "%d\n" "'$c"
32

But running the script line with -vx on shows that the data getting to this line is wrong ( I won't paste this output )

So I figure it is the read that is wrong. The default EOL delimiter for read is newline, so I tried altering that. This seems to work

while IFS= read -d\0 -r -n1 c; do ch=$(LC_CTYPE=C printf "%d\n" "'$c") ; echo "ch=$ch"; done < input_file_name
Related Question