How to Read the Help of a Shell Script in Linux
Read or die friends. The read command is just as of import equally positional parameters and the echo command. How else are you going to take hold of user input, accept passwords, write functions, loop, and peek into file descriptors? Read on.
What is read?
Read is a bash builtin command that reads the contents of a line into a variable. It allows for word splitting that is tied to the special shell variable IFS. It is primarily used for catching user input but can exist used to implement functions taking input from standard input.
Bash read builtin control assist
Before we dive into how to utilise the read command in fustigate scripts, here is how we go help. There you should see all the options available for the read command along with descriptions that we will attempt to cover in the examples.
Control line
Output
read: read [-ers] [-a assortment] [-d delim] [-i text] [-n nchars] [-N nchars]
[-p prompt] [-t timeout] [-u fd] [name ...]
Read a line from the standard input and carve up 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 first word is assigned to the offset Name, the second
word to the second NAME, and so on, with any leftover words assigned to
the last NAME. Just the characters found 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 proceed until the first grapheme of DELIM is read, rather
than newline
-e use Readline to obtain the line in an interactive beat out
-i text use TEXT as the initial text for Readline
-n nchars render subsequently reading NCHARS characters rather than waiting
for a newline, but honor a delimiter if fewer than
NCHARS characters are read earlier the delimiter
-N nchars return just after reading exactly NCHARS characters, unless
EOF is encountered or read times out, ignoring whatsoever
delimiter
-p prompt output the string PROMPT without a abaft newline before
attempting to read
-r do not allow backslashes to escape any characters
-s practise not repeat input coming from a terminal
-t timeout time out and return failure if a complete line of
input is not read within TIMEOUT seconds. The value of the
TMOUT variable is the default timeout. TIMEOUT may be a
fractional number. If TIMEOUT is 0, read returns
immediately, without trying to read whatsoever information, returning
success just if input is bachelor on the specified
file descriptor. The leave condition 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 zero, unless end-of-file is encountered, read times out
( in which instance it'south greater than 128), a variable assignment err
Catching user input
Interactive bash scripts are cypher without catching user input. The read builtin provides methods that user input may be caught within a bash script.
Communicable a line of input
To catch a line of input NAMEs and options are not required by read. When Proper noun is not specified, a variable named Answer is used to store user input.
Commands
{
echo -n "Blazon something and press enter: ";
read;
echo You lot typed ${Answer}
}
Output
Type something and press enter: something(newline)
You typed something
Catching a word of input
To catch a give-and-take of input, the -d pick is required. In the instance of a word we would set -d to a space, read '-d '. That is when the user presses the space bar read will load REPLY with the word.
Note that when the -d option is set, the backspace does not work as expected. To backspace, while trying to grab a word of input, the -e option may exist used, read -e '-d '.
Commands
{
echo -n "Type something and hit space: ";
read '-d ';
echo "";
repeat "You 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 ever accomplish this using the repeat builtin. All the same, it turns out there is an selection using read.
Prompt user for a give-and-take
In catching a give-and-take of input, we used repeat to write Type something and hit infinite: to standard output before read '-d '. The -p option allows a message to be displayed before reading from standard input.
Commands
{
read -p 'Type something and hitting space: ' '-d ';
echo "";
repeat "You typed ${Answer}"
}
Output
Blazon something and hit space: something(space)
Y'all typed something
Prompt user for a surreptitious
When catching user input without it showing up int the terminal, the -southward option comes in handy. read -south -p allows you lot to catch and hide user input as follows.
Commands
{
read -southward -p 'Type something I promise to proceed it a secret: '
echo "";
echo "Your undercover is condom with me" ; unset Reply ;
echo "${REPLY}"
}
Output
Blazon something I hope to keep information technology a secret:
Your secret is safe with me
Functions using read
Here are examples of functions in bash that use read and standard input
Core concept
Functions using read brand use of piped standard input and parameters. Main input to be procedure such every bit lines in a file are passed in through standard input via a pipage. Other input if-any and choice are passed in every bit parameters.
read -t 1 NAME1 NAME2 ...
read is a builtin command
-t 1 prevent the bash script from waiting indefinitely for a line to be returned through standard input. If standard input is initially empty, the part returns with an exit code of 142 signifying that no date was read inside the set up timeout period
NAME1 NAME2 are variable names
... many variable names may exist listed
At present that the groundworks are set, let'southward see what familiar functions look like implemented using read.
Bring together role using read
Suppose we want a join part that takes a list of words and returns another listing of words joined by a delimiter. Here is how we may implement a join function using read.
Script
#!/bin/bash
## join
## version 0.0.2 - fix recursion parameters
##################################################
join ( ) { { local indelimiter; indelimiter="${1- }" ; local outdelimiter;
outdelimiter="${ii-.}" ; }
local car
local cdr
local IFS
IFS="${indelimiter}"
read -t 1 machine cdr || return
test "${cdr}" || { repeat "${auto}" ; return ; }
echo "${car} ${outdelimiter} ${cdr}" | ${FUNCNAME} "${indelimiter}"
"${outdelimiter}"
}
##################################################
## generated past create-stub2.sh v0.1.2
## on Mon, 17 Jun 2019 12:24:59 +0900
## run across <https://github.com/temptemp3/sh2>
##################################################
Source: join.sh
Command line
Output
Control line
repeat a b | bring together | join . \|
Output
Map functions using read
Suppose we want a map function that takes a list and returns another list containing the same number of elements that are modified by another part. Hither is how nosotros may implement a map role using read.
Script
#!/bin/fustigate
## map
## version 0.0.ane - initial
##################################################
map( ) { { local function_name ; function_name="${1}" ; }
local car
local cdr
local IFS
IFS="${indelimiter- }"
read -t 1 car cdr || return
test "$( declare -f ${function_name} )" || return
test "${car}" || { truthful ; render ; }
${function_name} ${car}
echo "${cdr}" | ${FUNCNAME} "${function_name}"
}
##################################################
## generated by create-stub2.sh v0.ane.2
## on Tue, xviii Jun 2019 08:33:49 +0900
## see <https://github.com/temptemp3/sh2>
##################################################
Source: map.sh
Commands
prisoner of war( ) { local -i i=${ane} ; echo $( ( i ** two ) ) ; }
echo { 1..10 } | map pow
Output
1
4
9
16
25
36
49
64
81
100
Filter office using read
Suppose we desire a filter function that takes a list and returns a sublist of elements satifying weather gear up past another part. Here is how we may implement a filter function using read.
Script
#!/bin/bash
## filter
## version 0.0.ane - initial
##################################################
filter( ) { { local function_name ; function_name="${1}" ; }
local car
local cdr
local IFS
IFS="${indelimiter- }"
read -t 1 car cdr || render
examination "$( declare -f ${function_name} )" || return
exam "${car}" || { true ; render ; }
${function_name} "${machine}" || echo -north "${machine} "
echo "${cdr}" | ${FUNCNAME} "${function_name}"
}
##################################################
## generated past create-stub2.sh v0.1.2
## on Tue, 18 Jun 2019 xiii:19:54 +0900
## run across <https://github.com/temptemp3/sh2>
##################################################
Source: filter.sh
Commands
odd( ) { local -i i=${ane} ; examination ! $( ( i % 2 ) ) -eq ane ; }
echo { one..10 } | filter odd
Output
Loops using read
Loops using read permit you 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 function (lhs) that can generate lines in a file that can be looped through using read and a while loop.
Construct
lhs | while read
exercise
true
washed
lhs is a command that returns a list of lines
Commands
seq 5 | while read i
do
echo ${i}
done
Output
Bones while read loop for the righthand side (rhs)
We have a file (rhs) with lines that can be looped through using read and a while loop.
Construct
while read
do
true
done < rhs
rhs is a file containing lines
Commands
seq 5 > rhs
while read i
do
repeat ${i}
done < rhs
Output
1
ii
iii
4
five
Custom lhs while loop using read
We take a stream of words that we would like to loop through using read.
Construct
(
IFS=" "
lhs | while read
do
true
done
)
lhs is a list of words
Commands
(
IFS=" "
repeat { 1..5 } | while read i
do
echo "${i}
done
)
Output
Reading from any fd instead of standard input
The read builtin choice frequently left untouched is the one that allows you lot to specific what file descriptor to read from, read -u FD. By default FD is taken to be standard input.
Core concept
When a file opened file descriptors are assigned. IO redirection in bash let a file to be left open with a specific file descriptor. We are immune to write to the file, read from it, and close information technology when nosotros are done.
_ ( )
{
true cat /dev/null > myfifo; # empty myfifo
exec 3 < myfifo; # open file myfifo as fd 3
echo "Hi, Earth! - from fd iii" > myfifo; # write to myfifo
read -u 3; # read line from fd iii
exec 3 >&-; # shut fd iii
echo ${REPLY} # output line read from fd 3 before closing
}
_ # Hello, World! 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.
Control line
bash linuxhint.com/build/examination-read-fd.sh railroad train 10
Output
initializing fds ...
initializing fd iii ...
fd 3 intialized
initializing fd four ...
fd 4 intialized
fds intialized
reading from fd 3 and 4 ...
iv 3
fds before cleaning upward
0 ane 2 3 iv five
cleaning up ...
cleaning up fds ...
done cleaning up fds
fds after cleaning upward
0 i two 3
Skip role using read -u FD
If you are running
uname -a
MINGW64_NT-10.0 DESKTOP-XVVVVVV ii.vii.0( 0.307 / v / iii )
2017-02-17 14:20 x86_64 Msys
bash --version
GNU bash, version 4.4.12( 1 )-release (x86_64-pc-msys)
it may be possible due to a problems to implement a skip office that skips the following line in a fustigate script exterior of functions before the script source is read. Notation that it does not work on most systems. For instance,
uname -a
Linux iv.ix.0-8-amd64 #1 SMP Debian 4.ix.144-three.1 (2019-02-19) x86_64 GNU/Linux
fustigate --version
GNU bash, version 4.4.12( 1 )-release (x86_64-pc-linux-gnu)
skip does not wing.
Function
skip ( ) { read -u 31 ; }
Commands
skip
echo line skipped
truthful
Output
Bottom line
The read builtin in fustigate does more than catch user input. It can be used in functions, loops and exchanges between file descriptors used in bash scripts. On occasion exploration using read and file descriptors may yield Easter eggs.
Source: https://linuxhint.com/bash_read_command/
0 Response to "How to Read the Help of a Shell Script in Linux"
Post a Comment