09 January 2022

Bash read builtin is a utility that can read a line from the standard input and split it into fields.

I found it usefull in bash script in order to:
- receive a user response and use for the following process
- separate a string in multiple fields

Note: all example below could be execute in a container:

docker run -it  ubuntu /bin/bash

Receive a user response and use for the following process

CHOOSED_CHOCOLATE=0
while true; do
    read -r -p "Do you want chocolate? (Y/N): " ANSWER
    case $ANSWER in
        [Yy]* ) CHOOSED_CHOCOLATE=1; break;;
        [Nn]* ) CHOOSED_CHOCOLATE=0; break;;
        * ) echo "Please answer Y or N.";;
    esac
done
echo "CHOOSED_CHOCOLATE: ${CHOOSED_CHOCOLATE}"

Explanation about example:
* -r: do not allow backslashes to escape any characters
* -p: output the string "Do you want chocolate? (Y/N): " without a trailing newline before attempting to read
* ANSWER: The line is split into fields as with word splitting, and the first word is assigned to ANSWER

Separate a string in multiple fields

IFS="|" read -r VAR1 VAR2 <<< "ipsedixit|ipsedixit2"
echo "var1: ${VAR1} - var2: ${VAR2}"

Explanation about example:
* IFS="|": set field separator as | character
* <<<: The word undergoes tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, and quote removal. See also 3.6.7 Here Strings - GNU documentation

References

read --help