How to Use Read Command in Shell Script

Bash read builtin command

Updated: 12/31/2020 by Computer Promise

read command

On Unix-like operating systems, read is a builtin command of the Bash shell. Information technology reads a line of text from standard input and splits it into words. These words can then exist used every bit the input for other commands.

Description

read reads a single line from standard input, or from the file descriptor fd if the -u option is used (see -u, below).

By default, read considers a newline character every bit the end of a line, but this can be changed using the -d option.

After reading, the line is divide into words according to the value of the special crush variable IFS, the internal field separator. By default, the IFS value is "space, tab, or newline". If read encounters readable characters before encountering an IFS, information technology considers those characters to exist a word. (For more than information nearly the IFS, see word splitting in bash.)

Tip

To preserve white space at the beginning or the end of a line, it'due south common to specify IFS= (with no value) immediately earlier the read command. Later on reading is completed, the IFS returns to its previous value. For more than nigh this, see the examples below.

read assigns the beginning word it finds to name, the second discussion to name2, etc. If there are more words than names, all remaining words are assigned to the last name specified. If but a unmarried name is specified, the entire line is assigned to that variable.

If no name is specified, the input is stored in a variable named Respond.

Syntax

          read          [-ers] [-a          assortment] [-d          delim] [-i          text] [-due north          nchars] [-N          nchars]      [-p          prompt] [-t          timeout] [-u          fd] [proper name          ...] [name2          ...]

Options

The read builtin command takes the following options:

-a array Store the words in an indexed array named assortment. Numbering of array elements starts at zero.
-d delim Prepare the delimiter character to delim. This character signals the end of the line. If -d is not used, the default line delimiter is a newline.
-e Get a line of input from an interactive shell. The user manually inputs characters until the line delimiter is reached.
-i text When used in conjunction with -e (and but if -s is not used), text is inserted as the initial text of the input line. The user is permitted to edit text on the input line.
-north nchars Stop reading after an integer number nchars characters are read, if the line delimiter has not been reached.
-N nchars Ignore the line delimiter. Stop reading only after nchars characters are read, EOF is reached, or read times out (see -t).
-p prompt Impress the string prompt, without a newline, before showtime to read.
-r Use "raw input". Specifically, this option causes read to interpret backslashes literally, rather than interpreting them every bit escape characters.
-southward Do not repeat keystrokes when read is taking input from the last.
-t timeout Time out, and return failure, if a complete line of input is not read within timeout seconds. If the timeout value is zero, read will not read any information, but returns success if input was available to read. If timeout is not specified, the value of the shell variable TMOUT is used instead, if it exists. The value of timeout are partial numbers, east.g., 3.5.
-u fd Read from the file descriptor fd instead of standard input. The file descriptor should be a small-scale integer. For information most opening a custom file descriptor, see opening file descriptors in bash.

Exit condition

The exit condition of read is zero unless EOF is encountered, the timeout is exceeded, an mistake occurs assigning a value to proper name, or the file descriptor provided to -u is invalid.

If a timeout is exceeded, the exit condition is greater than 128.

Examples

while read; do echo "$REPLY"; done

read takes information from the terminal. Type whatever you'd like, and press Enter. The text is echoed on the next line. This loop continues until you press Ctrl+D (EOF) on a new line. Because no variable names were specified, the unabridged line of text is stored in the variable Answer.

while read text; exercise echo "$text"; done

Same every bit above, using the variable name text.

while read -ep "Type something: " -i "My text is " text; do    echo "$text"; done

Provides a prompt, and initial text for user input. The user tin can erase "My text is ", or leave as part of the input. Typing Ctrl+D on a new line terminates the loop.

echo "How-do-you-do, world!" | (read; repeat "$Respond")

Enclosing the read and echo commands in parentheses executes them in a dedicated subshell. This allows the Respond variable to be accessed by both read and echo. For more information, run across fustigate control execution environments: subshells.

echo "one two iii four" | while read word1 word2 word3; do   echo "word1: $word1"   repeat "word2: $word2"   echo "word3: $word3" done

Echo "i ii three four" and pipe it to the while loop, where read reads the first give-and-take into word1, the 2d into word2, and everything else into word3. Output:

word1: 1 word2: 2 word3: 3 four
echo "one two three iv" | while read -a wordarray; do   echo ${wordarray[ane]} done

Same as to a higher place, but assign the words to the elements of an indexed array, wordarray. The numbering starts at zero, and so ${wordarray[ane]} returns the second discussion. For more information, see bash arrays. Output:

2
while IFS= read -r -d $'\0' file; do   echo "$file" done < <(find . -print0)

The above commands are the "proper" way to utilize find and read together to process files. It's particularly useful when you lot want to exercise something to a lot of files that have odd or unusual names. Allow'southward take a look at specific parts of the to a higher place example:

while IFS=

IFS= (with nothing subsequently the equals sign) sets the internal field separator to "no value". Spaces, tabs, and newlines are therefore considered office of a discussion, which preserves white space in the file names.

Notation that IFS= comes afterward while, ensuring that IFS is altered just inside the while loop. For case, information technology won't bear upon find.

read -r

Using the -r pick is necessary to preserve any backslashes in the file names.

-d $'\0'

The -d option sets the newline delimiter. Here, we're setting it to the NULL character, ASCII code zero. (An escaped zilch enclosed in single quotes, preceded by a dollar sign, is interpreted by bash equally Cypher. For more information, see: Expanding strings with interpreted escapes in the bash documentation.)

Nosotros're using NULL as the line delimiter because Linux file names can contain newlines, and so we need to preserve them. (This sounds awful, merely yes, it happens.)

However, a Naught can never be part of a Linux file proper name, so that's a reliable delimiter to use. Luckily, find can utilise Aught to delimit its results, rather than a newline, if the -print0 option is specified:

< <(find . -print0)

Here, detect . -print0 creates a listing of every file in and nether . (the working directory) and delimit all file names with a Naught. When using -print0, all other arguments and options must precede it, then brand sure it's the last role of the command.

Enclosing the notice control in <( ... ) performs process substitution: the output of the command tin be read like a file. In turn, this output is redirected to the while loop using the kickoff "<".

Every iteration of the while loop, read reads 1 give-and-take (a single file name) and puts that value into the variable file, which we specified every bit the last argument of the read command.

When there are no more file names to read, read returns false, which triggers the end of the while loop, and the command sequence terminates.

while — Execute a fix of actions while a certain condition is true.
find — Find files inside a directory bureaucracy.

hewettswitted1985.blogspot.com

Source: https://www.computerhope.com/unix/bash/read.htm

0 Response to "How to Use Read Command in Shell Script"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel