Search code examples
bashcharsleepifs

bash: reading text from a string one character at a time, with whitespace


I'm bored, and decided to write a script for a text-based adventure of mine using bash. Basically, it's supposed to animate a typewriter in certain cases for dramatic storytelling. I can do this manually in a file like so:

sleep 0.1 
echo -n "h"
sleep 0.1 
echo -n "e"
sleep 0.1 
echo -n "l"
sleep 0.1 
echo -n "l"
sleep 0.1 
echo -n "o"

As you can imagine, it's dreadfully tedious. Instead, I want to pull characters from a string (or file) one character at a time, and apply the sleep command to each character.

So far, I have the following, that reads from a file. IFS= allows the spaces to retain, but not any other type of whitespace (such as newline).

IFS=
while read -n1 achar
do
   echo $achar
done < aFile

Is there a way I can use this to get all whitespace? As a bonus question, can you tell me how to apply this to a user-defined script, so I don't have to read from a separate file? So, for example, lets say I have a string called "hello", and I can simply pass it to my function to animate as a typewriter whenever I run my file in the bash terminal.

Any help would be appreciated. Thanks!


Solution

  • How about

    #!/bin/bash
    
    function typewriter
    {
        text="$1"
        delay="$2"
    
        for i in $(seq 0 $(expr length "${text}")) ; do
            echo -n "${text:$i:1}"
            sleep ${delay}
        done
    }
    
    
    typewriter "Typewriters are cool." .1
    echo # <-- Just for a newline