Bash: read text from a string one character at a time, with space

I'm bored and I decided to write a script for a text adventure using bash. Basically, he should animate a typewriter in some cases for a dramatic narrative. I can do this manually in a file as follows:

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, this is terribly tiring. Instead, I want to draw characters from a line (or file) one character at a time and apply a sleep command for each character.

So far, I have the following which is read from a file. IFS = allows you to save spaces, but not any other type of spaces (e.g. newline).

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

Is there a way I can use this to get all the spaces? As a bonus question, can you tell me how to apply this to a custom script, so I don't need to read from a separate file? So, for example, let's say I have a line called "hello" and I can just pass it to my animation function as a typewriter whenever I run my file in a bash terminal.

Any help would be greatly appreciated. Thanks!

+6
source share
3 answers

What 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 
+8
source

To answer the original question, you also need to use an empty delimiter:

 #!/bin/bash getc() { IFS= read -r -n1 -d '' " $@ " } typewriter() { while getc ch; do sleep 0.1; echo "$ch" done } 

In principle, read will dwell on new lines (the default delimiter), even if it has not yet consumed enough characters. The -r flag also indicates that it will leave only a backslash.

Full explanation here: http://jayferd.us/posts/2011-01-12-bash-adventures-read-a-single-character-even-if-its-a-newline

+1
source

@derp no you need to use tr -s [:blank:] to compress multiple blanks into one.

NTN.

0
source

Source: https://habr.com/ru/post/914945/


All Articles