Read User Input as Integer in Bash

Read or die friends. The read command is but equally important as positional parameters and the echo command. How else are you lot going to catch user input, accept passwords, write functions, loop, and peek into file descriptors? Read on.

What is read?

Read is a bash builtin control that reads the contents of a line into a variable. It allows for word splitting that is tied to the special trounce variable IFS. It is primarily used for catching user input only can exist used to implement functions taking input from standard input.

Bash read builtin control help

Before we dive into how to apply the read command in bash scripts, hither is how nosotros get help. There you should encounter all the options available for the read command along with descriptions that we will attempt to encompass in the examples.

Control line

Output

read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars]
[-p prompt] [-t timeout] [-u fd] [proper noun ...]

Read a line from the standard input and split it into fields.

Reads a single line from the standard input, or from file descriptor FD
if the -u option is supplied.  The line is split into fields as with word
splitting, and the start word is assigned to the showtime Proper name, the 2d
word to the second NAME, and and then on, with whatever leftover words assigned to
the final NAME.  Merely the characters constitute in $IFS are recognized as word
delimiters.

If no NAMEs are supplied, the line read is stored in the Respond variable.

Options:
-a array  assign the words read to sequential indices of the array
variable Assortment, starting at zero
-d delim continue until the starting time character of DELIM is read, rather
than newline
-e        use Readline to obtain the line in an interactive beat out
-i text   use TEXT every bit the initial text for Readline
-n nchars return afterwards reading NCHARS characters rather than waiting
for a newline, only honor a delimiter if fewer than

NCHARS characters are read before the delimiter
-North nchars render only later on reading exactly NCHARS characters, unless
EOF is encountered or read times out, ignoring whatever
delimiter
-p prompt output the string PROMPT without a abaft newline before
attempting to read
-r do not let backslashes to escape whatsoever characters
-due south do not echo input coming from a terminal
-t timeout fourth dimension out and return failure if a consummate line of
input is not read within TIMEOUT seconds.  The value of the
TMOUT variable is the default timeout.  TIMEOUT may be a
partial number.  If TIMEOUT is 0, read returns
immediately, without trying to read any data, returning
success but if input is available on the specified
file descriptor.  The go out status is greater than 128
if the timeout is exceeded
-u fd read from file descriptor FD instead of the standard input

Exit Status:
The return lawmaking is null, unless finish-of-file is encountered, read times out
( in which example information technology's greater than 128), a variable assignment err

Catching user input

Interactive bash scripts are zip without communicable user input. The read builtin provides methods that user input may be caught within a bash script.

Catching a line of input

To catch a line of input NAMEs and options are not required by read. When NAME is non specified, a variable named Answer is used to store user input.

Commands

{
echo -northward "Blazon something and press enter: ";
read;
echo Y'all typed ${REPLY}
}

Output

Blazon something and press enter: something(newline)
You typed something

Catching a discussion of input

To catch a word of input, the -d pick is required. In the case of a word nosotros would fix -d to a space, read '-d '. That is when the user presses the infinite bar read will load REPLY with the give-and-take.

Notation that when the -d pick is set, the backspace does non work every bit expected. To backspace, while trying to catch a word of input, the -e selection may be used, read -e '-d '.

Commands

{
echo -n "Type something and hit space: ";
read '-d ';
echo "";
echo "You lot typed ${Answer}"
}

Output

Type something and hit space: something(space)
You typed something

Prompt user

In interactive fustigate scripts prompting a user may require a message to tell the user what input is expected. Nosotros can always accomplish this using the echo builtin. Withal, it turns out there is an option using read.

Prompt user for a word

In catching a word of input, nosotros used echo to write Type something and hit space: to standard output before read '-d '. The -p option allows a message to exist displayed before reading from standard input.

Commands

{
read -p 'Type something and hit space: ' '-d ';
echo "";
repeat "You typed ${REPLY}"
}

Output

Type something and hit space: something(space)
Yous typed something

Prompt user for a undercover

When catching user input without it showing up int the terminal, the -due south pick comes in handy. read -s -p allows you to take hold of and hibernate user input as follows.

Commands

{
read -s -p 'Type something I promise to proceed it a surreptitious: '
echo "";
echo "Your hugger-mugger is safe with me" ; unset Answer ;
echo "${REPLY}"
}

Output

Type something I promise to go along information technology a secret:
Your cloak-and-dagger is condom with me

Functions using read

Here are examples of functions in bash that use read and standard input

Core concept

Functions using read make use of piped standard input and parameters. Master input to be process such as lines in a file are passed in through standard input via a pipe. Other input if-any and option are passed in as parameters.

read -t ane NAME1 NAME2 ...

read is a builtin command

-t i prevent the bash script from waiting indefinitely for a line to be returned through standard input. If standard input is initially empty, the function returns with an exit code of 142 signifying that no engagement was read within the ready timeout menses

NAME1 NAME2 are variable names

... many variable names may be listed

Now that the groundworks are set, let'due south encounter what familiar functions look like implemented using read.

Join part using read

Suppose we want a bring together function that takes a list of words and returns some other list of words joined past a delimiter. Here is how we may implement a bring together function using read.

Script

#!/bin/bash
## bring together
## version 0.0.2 - fix recursion parameters
##################################################
join ( ) { { local indelimiter; indelimiter="${1- }" ; local outdelimiter;
outdelimiter="${2-.}" ; }
local machine
local cdr
local IFS
IFS="${indelimiter}"
read -t 1 motorcar cdr || return
test "${cdr}" || { echo "${car}" ; return ; }
echo "${motorcar} ${outdelimiter} ${cdr}" | ${FUNCNAME} "${indelimiter}"
"${outdelimiter}"
}
##################################################
## generated past create-stub2.sh v0.1.2
## on Mon, 17 Jun 2019 12:24:59 +0900
## see <https://github.com/temptemp3/sh2>
##################################################

Source: join.sh
Command line

Output

Control line

echo a b | bring together | bring together . \|

Output

Map functions using read

Suppose we want a map function that takes a listing and returns another list containing the same number of elements that are modified by some other office. Hither is how we may implement a map role using read.

Script

#!/bin/bash
## map
## version 0.0.one - initial
##################################################
map( ) { { local function_name ; function_name="${1}" ; }
local machine
local cdr
local IFS
IFS="${indelimiter- }"
read -t one automobile cdr || return
test "$( declare -f ${function_name} )" || return
test "${automobile}" || { true ; render ; }
${function_name} ${car}
echo "${cdr}" | ${FUNCNAME} "${function_name}"
}
##################################################
## generated past create-stub2.sh v0.ane.2
## on Tue, 18 Jun 2019 08:33:49 +0900
## come across <https://github.com/temptemp3/sh2>
##################################################

Source: map.sh
Commands

pw( ) { local -i i=${1} ; repeat $( ( i ** 2 ) ) ; }
repeat { one..10 } | map prisoner of war

Output

1
iv
9
sixteen
25
36
49
64
81
100

Filter function using read

Suppose nosotros want a filter function that takes a list and returns a sublist of elements satifying atmospheric condition set past another function. Here is how we may implement a filter office using read.

Script

#!/bin/bash
## filter
## version 0.0.1 - initial
##################################################
filter( ) { { local function_name ; function_name="${one}" ; }
local motorcar
local cdr
local IFS
IFS="${indelimiter- }"
read -t i automobile cdr || return
test "$( declare -f ${function_name} )" || return
examination "${auto}" || { true ; return ; }
${function_name} "${car}" || echo -due north "${car} "
echo "${cdr}" | ${FUNCNAME} "${function_name}"
}
##################################################
## generated by create-stub2.sh v0.1.2
## on Tue, 18 Jun 2019 thirteen:19:54 +0900
## run into <https://github.com/temptemp3/sh2>
##################################################

Source: filter.sh

Commands

odd( ) { local -i i=${1} ; test ! $( ( i % 2 ) ) -eq ane ; }
echo { i..ten } | filter odd

Output

Loops using read

Loops using read allow y'all to iterate through lines of a file that is to exist generated or already exists.

Basic while read loop for the lefthand side (lhs)

We have a command or part (lhs) that can generate lines in a file that can be looped through using read and a while loop.

Construct

lhs | while read
practice
truthful
done
lhs is a command that returns a list of lines

Commands

seq 5 | while read i
do
repeat ${i}
done

Output

Basic while read loop for the righthand side (rhs)

Nosotros have a file (rhs) with lines that can be looped through using read and a while loop.

Construct

while read
exercise
true
done < rhs

rhs is a file containing lines

Commands

seq v > rhs
while read i
do
echo ${i}
done < rhs

Output

1
two
3
4
five

Custom lhs while loop using read

We have a stream of words that nosotros would like to loop through using read.

Construct

(
IFS=" "
lhs | while read
do
truthful
done
)

lhs is a listing of words

Commands

(
IFS=" "
echo { 1..5 } | while read i
exercise
echo "${i}
done
)

Output

Reading from whatever fd instead of standard input

The read builtin option often left untouched is the one that allows you to specific what file descriptor to read from, read -u FD. By default FD is taken to be standard input.

Cadre concept

When a file opened file descriptors are assigned. IO redirection in bash permit a file to be left  open with a specific file descriptor. We are immune to write to the file, read from it, and shut it when we are done.

_ ( )
{
cat /dev/nil > myfifo; # empty myfifo
exec 3 < myfifo; # open file myfifo every bit fd 3
echo "How-do-you-do, World! - from fd iii" > myfifo; # write to myfifo
read -u 3; # read line from fd 3
exec 3 >&-; # close fd 3
echo ${Reply} # output line read from fd 3 before endmost
}
_ # Hullo, Earth! from fd 3

Building a train with file descriptors and read -u FD

Just for fun I decided to build a train with file descriptors and read -u FD. To each file descriptor a number is written. Each file descriptor reads from the file descriptor one below and appends to itself.

Command line

bash linuxhint.com/build/examination-read-fd.sh train x

Output

initializing fds ...
initializing fd 3 ...
fd iii intialized
initializing fd 4 ...
fd 4 intialized
fds intialized
reading from fd 3 and 4 ...
4 3
fds earlier cleaning upward
0 1 2 3 4 five
cleaning upward ...
cleaning up fds ...
done cleaning upward fds
fds after cleaning up
0 one ii 3

Skip function using read -u FD

If you are running

uname -a
MINGW64_NT-ten.0 DESKTOP-XVVVVVV 2.7.0( 0.307 / five / iii )
2017-02-17 xiv:20 x86_64 Msys
bash --version
GNU bash, version iv.4.12( i )-release (x86_64-pc-msys)

information technology may be possible due to a bug to implement a skip function that skips the following line in a bash script exterior of functions earlier the script source is read. Note that it does not piece of work on most systems. For instance,

uname -a
Linux 4.nine.0-8-amd64 #ane SMP Debian 4.9.144-3.1 (2019-02-nineteen) x86_64 GNU/Linux
bash --version
GNU bash, version 4.4.12( one )-release (x86_64-pc-linux-gnu)

skip does not fly.

Function

skip ( ) { read -u 31 ; }

Commands

skip
echo line skipped
true

Output

Lesser line

The read builtin in bash does more than than catch user input. It can exist used in functions, loops and exchanges betwixt file descriptors used in bash scripts. On occasion exploration using read and file descriptors may yield Easter eggs.

Nearly the author

A programmer and advocate of shell scripting and vim. His works include automation tools, static site generators, and web crawlers written in bash. For piece of work he tools with cloud computing, app development, and chatbots. He codes in fustigate, python, or php, merely is open to offers.

talleytrainsomill.blogspot.com

Source: https://linuxhint.com/bash_read_command/

0 Response to "Read User Input as Integer in Bash"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel