Problem with reading characters

Hello,
if I try this (in bash):

#!/bin/bash
cat leercaracter.sh | while read linea
do
   # read character by character
   echo $linea | while read -n 1 caracter
   do
      echo $caracter
   done
done

New lines, spaces, tabs aren't showed by echo.

How can I 'echo' those characters?

Thank you

Try to use quotes around the variable, like:

echo "$caracter"

I tried that and doesn't work...
With strong quotes the effect is $caracter (literal).

Try This

#!/bin/bash
while read line
do
#echo $line
echo "$line" | while read -n 1 caracter
do
      echo $caracter
   done
done < leercaracter.sh 

Try to quote the variable in the first echo too, that should preserve all blanks and tabs. The newline characters are lost in the outer loop, because you read the input file line by line and the terminating newline is not written to the variable by read.

Thank you to all.

Later I will test the solutions. Now, (in my work) I have ksh but not (and is impossible to install) bash...
thank you again.

This is a great forum.

---------- Post updated at 05:56 PM ---------- Previous update was at 12:50 PM ----------

No, the problem continues....

If I code this:

#!/bin/bash

cat leerfichero.sh | while read linea
do
   echo ""
   echo "$linea" | while read -n 1 caracter
   do
      echo -n "$caracter"
   done
done

I get:

:
~$ bash leerfichero.sh 

#!/bin/bash

catleerfichero.sh|whilereadlinea
do
echo""
echo"$linea"|whileread-n1caracter
do
echo-n"$caracter"
done

The same result with the other opcion:

:~/shell/ejercicios$ bash leerfichero.sh 

#!/bin/bash

catleerfichero.sh|whilereadlinea
do
echo""
echo"$linea"|whileread-n1caracter
do
echo-n"$caracter"
done

I don't understand!

You need to set IFS to "" to tell read to not break arguments on whitespace. This property is occasionally useful -- if you set IFS="," you can read in values delimited by commas instead of space-separated ones...

Note I don't set IFS globally anywhere here, since you usually expect it to break on whitespace.

So, to make your program work:

#!/bin/bash

cat leerfichero.sh | while IFS="" read linea
do
   echo ""
   echo "$linea" | while IFS="" read -n 1 caracter
   do
      echo -n "$caracter"
   done
done

...or better yet, use a redirection to avoid a Useless Use Of Cat:

#!/bin/bash

while IFS="" read linea
do
   echo ""
   echo "$linea" | while IFS="" read -n 1 caracter
   do
      echo -n "$caracter"
   done
done < leerfichero.sh

...or, even better, use string operations to get the nth character, avoiding pipes and external calls completely. This is much, much faster.

#!/bin/bash
while IFS="" read linea
do
        echo

        for((N=0; N<${#linea}; N++))
        do
                echo -n "${linea:$N:1}"
        done
done < leerfichero.sh

Yes. Thank you very much. I didn't know the relation between IFS and read...
And a very interesting article about de useless use of...

Thank you again