If you directly use strings under a for loop, it will work per-word, not per-character. You need to use a while loop with read in order to parse letter-by-letter. Or introduce a numerical parameter that would iterate over the string.
In addition, when using read, you need to make sure that newlines and whitespaces arent interpreted as delimiters and force read to read one char at a time.
Here's a working version:
#!/bin/bash
test="this is a
test"
echo -n "$test" | while IFS= read -N 1 a; do
if [[ "$a" == $'\n' ]] ; then
echo "FOUND NEWLINE"
fi
printf "$a"
done
You could replace $'\n' with $'\012' or $'\x0a', since they all represent the same newline code. But it is not the same as \r - this stands for carriage return (return to the beginning of line). On Linux systems, newlines are represented using \n, but on Windows for example, they are represented by a sequence of \r\n instead. That is why if you had a text file from Windows, you could detect newlines also by searching for \r.
cat | while read line; do ...; done, you know there was a carriage return for each iteration. If your input can be files with\rwithout\n, just transform the filetr '\r' '\n'while processing the input. If you just need to know if there are multiple lines:wc -l. – nicerobot Dec 22 '11 at 20:14wc -lwill return 0; you should add that as an answer – Arcege Dec 23 '11 at 2:10