How to use the read command under Linux

  
                

The read command in Linux is mainly used to read and input terminals or files. It is also a command that will be used frequently. The following will give you a detailed introduction to the usage of the read command under Linux. Let's take a look at it.

I. Overview

read command receiving input standard input (keyboard), or other input file descriptors. After getting the input, the read command puts the data into a standard variable.

Second, use examples (only some commonly used options are listed here)

1. Basic reading

The code is as follows:

#! /bin/bash

echo -n “Enter your name:”#Parameter-n is not a line break, echo default is a newline

read name #Enter from keyboard

echo “hello $name, welcome to my program”

exit 0 # Exit the shell program.

It is equivalent to the following:

The code is as follows:

read -p“Enter your name:”name #-p parameter, allowed directly in the read command line Specify a prompt

The variable after the read above has only one name, and there can be more than one. If you input multiple data, the first data is given to the first variable, and the second data is given to the first data. Two variables. If the number of input data is too large, all the last remaining values ​​are given to the last variable, and if too little input does not end.

2. You can also not specify a variable in the read command line.

If you do not specify a variable, the read command will place the received data in the environment variable REPLY

The code is as follows:

read -p “Enter a number”

echo $REPLY

3. Timing input

There is a potential danger in using the read command . The script is likely to stop and wait for the user's input. If you must continue execution regardless of whether you enter a data script, you can use the -t option to specify a timer that specifies the number of seconds the read command waits for input. When the timer is full, the read command returns a non-zero value (0 is the normal exit state);

The code is as follows:

#! /bin/bash

ifread -t 5 -p “please enter your name:”name

then

echo “hello $name, welcome to my script&rdquo ;

else

echo “sorry,too slow”

fi

exit 0
Previous12Next Total 2 Pages

Copyright © Windows knowledge All Rights Reserved