Linux bash user input

How to Read User Input in Bash [5 Practical Cases]

In Bash, one way to interact with users is by reading user input, which allows scripts and programs to accept data directly from the keyboard or other input sources. So, reading user input is a crucial aspect of creating interactive scripts. From this article, you will know how to read bash user inputs using the ‘read’ command with some practical cases.

Key Takeaways

  • Learning about the ‘read’ command.
  • Learning about practical cases of how to read user inputs.

Free Downloads

The ‘read’ Command

In Bash, the ‘read’ command is a built-in command used to read input from the user or from a specified input source. It then assigns the entered value to one or more variables for further script processing.

Command Syntax >

Useful Options

  • -s → Let the command perform in the ‘silent’ mode.
  • -n → Returns after reading the specified number of characters.
  • -t → Sets the time in seconds that the script should wait for the input from the user.
  • -r → Disables backlashes to escape characters.
  • -p → Shows a message to the user before the input prompt.

5 Cases of Reading User Inputs Using the ‘read’ Command

Bash uses the ‘read’ command to read user inputs. In this article, I will discuss some practical cases of how to create bash scripts to read user inputs.

Case 1: Read Single User Input Using Bash Script

In this case, I will show you how you can simply use the ‘read’ command to read a single user input. Please follow the below steps to check the process:

Steps to Follow >

➊ At first, launch an Ubuntu Terminal.

➋ Now, write the following command to open a file in the nano text editor:

File in the nano editor

➌ Afterward, write the following script in the nano editor:

#! /bin/bash echo “What’s your name?” read name echo “Hello, $name! Nice to meet you.”

Here, #! /bin/bash: ‘#!’, is called shebang or hashbang. It indicates the interpreter to be used for executing the script, in this case, it’s bash. Next, the ‘echo’ command echoes the quoted message. After that, the “read” command reads & stores the input from the user and assigns it to the variable “name”. In the last line, the “echo” command echoes the value stored in the “name” variable along with other parts of the message.

➍ Then, press CTRL+S to save the file & press CTRL+X to exit the nano editor.

➎ After that, use the following command to make the script executable:

  • chmod: Changes the permission of files and directories.
  • u+x: Argument with chmod command to add the executable permission for the user.
  • sh: File which you want to make executable.

➏ Finally, run the script by the following command:

Читайте также:  Bios настройка для линукс

Running Bash script for reading single input

In the above image, you can see that, I successfully ran the created “intro.sh” script. The script is showing a user interactive message ‘What’s your name?’. Later it has been read & displayed after the user has inserted the value ‘Joy’.

Case 2: Read Multiple User Inputs Using Bash Script

The ‘read’ command in Bash can read multiple variables at a time. For that, just provide a list of variable names separated by spaces, and the command will assign the corresponding inputs to each variable.

Script (info.sh) >

#! /bin/bash echo “Enter your name, age, and gender: ” read name age gender echo “Name: $name” echo “Age: $age” echo “Gender: $gender”

First, the ‘echo’ command prints a prompt message to the user, specifying the inputs expected. After that, The ‘read’ command reads the user’s input, which is then executed to contain three values separated by spaces. It assigns these values to the variables ‘name’, ‘age’, & ‘gender’ respectively. The next three lines display the value stored in these variables.

Now, run the script by the following command:

Running Bash script for reading multiple inputs

In the above image, you can see that, I successfully ran the created “info.sh” script. The script is showing a user interactive message for multiple inputs. Later these values have been read & displayed after the user has inserted the values ‘joy 20 male’ (separated by space).

Case 3: Read Input from a File in Bash

You can use the ‘read’ command within a loop to process each line of a file. In this case, the script will simply echo each line with a processing message, but you can perform any desired operations.

Script (file.sh) >

#! /bin/bash filename=”input.txt” while IFS=read -r line do echo “Processing: $line” # Performs actions on each line done < “$filename”

First, assign the file name you want to read from to the variable ‘filename’. Here, the file name is set to ‘input.txt’. Make sure the file exists in the same directory as the script or provide the full path to the file.

Then, the ‘while IFS=read -r line’ line initiates a ‘while’ loop that iterates over each line of the file. Where in ‘IFS=read -r line’, the ‘read’ command reads each line from the file and assigns it to the variable ‘line’. By setting ‘IFS= ’ and using the ‘-r’ option it is ensured that leading & trailing whitespaces are preserved, and backlashes are not interpreted as escape characters. And ‘do’ sets actions for the command.

Now, run the script by the following command:

Running Bash script for reading from a file

In the above image, you can see that, I successfully ran the created “file.sh” script. The script is reading & processing each line of the file ‘input.txt’. After reading, it is also displaying them one by one.

Case 4: Read User Password Securely Using Bash

Using the ‘read’ command with option ‘–silent’ or ‘-s’ you can assign any sensitive user information as the command option hides them without being displayed on the screen.

Script (password.sh) >

#! /bin/bash echo -n Enter your password: read -s password echo # Perform actions in silent mode echo “Password entered: $password”

The first line ‘echo -n “Enter your password: ”’, echoes the quoted message with, -n being used to prevent a newline character from being added. Then in ‘read -s password’, the option ‘-s’ lets operate the “read” command in silent mode. Thus, the user can enter a password without displaying the characters on the screen. After that “echo” prints a ‘newline’ just to maintain the readability. Finally, ‘echo “Password entered: $password”’, prints out the password that the user entered.

Читайте также:  Сбивается время после перезагрузки linux

Now, run the script by the following command:

Running bash script for user password input

In the above image, you can see that, I successfully ran the created “password.sh” script. The script is showing a user interactive message ‘Enter your password’. Later, the user enters the password but the command reads it in ‘silent mode’ without displaying it. Which we can see after printing the value.

Case 5: Create an Interactive Prompt for Multiple Input Types

You can also write a bash program to generate prompts for multiple inputs. In this case, the prompt will ask the user three different questions and print them at the end.

Script (prompt.sh) >

#!/bin/bash echo "Welcome. What should we call you: " read var_name echo “It’s nice to meet you” $var_name read -p “Enter your age: ” number echo “So, you are a $number year old!” echo ”Do you like bash programming?(y/n)” read echo “That’s good to know, thank you.”

The first line echoes a message. In the next line, the script takes the input as a variable and prints it. Then, in the next line, the “read” command prints the prompt and takes a numeric value from the user using the -p (prompt) option, and prints this number in the next line. At last, comes the yes/no question to the user, which is read by default, and the program ends with a thank-you message.

Now, run the script by the following command:

Running bash script for prompt input

First, it welcomed the user and asked for the user name, in the next line the user inserted the value ‘jane’. After that, the program prints “It’s nice to meet you jane”. Where ‘jane’ is the variable value. Then asks for the user’s age by “Entering your age” and the user inserted 12. The next line prints the user’s age with the line “So, you are a 12 year old!”. Finally, asks a yes/ no question, and the user inserts “Yes” by entering the letter “y”. After reading the message “That’s good to know, thank you.” is displayed.

Conclusion

To sum up, learning to create interactive scripts is a mandatory Bash scripting task. And for that, you have to learn to read user inputs. Hope this article helps in attaining the necessary knowledge.

People Also Ask

To read the user input, use the built-in command called ‘read’. As it takes input from the user & assigns it to the variable.

To enter user input in a shell script, you can use the ‘read’ command. For that use the command’s basic syntax, ‘read variable_name’. When the ‘read’ command is executed, it waits for the user to input a value which then is stored in the specified variable for further processing of the script.

In Bash, there are multiple ways to pass input to a script or a command. Such as Command-Line Arguments, Standard Input or Piping, and User Prompts (Interactive inputs).

In a shell script, the special variable ‘$1’ represents the first command-line argument passed to the script. You can also use other special variables like ‘$2’, ‘$3’, and so on to access subsequent command-line arguments if they are provided.

The command-line interface in the Unix-based Bash shell, Bash Prompt, displays the user’s current working directory and provides a location to enter commands. The prompt indicates that the shell is prepared to handle the next command you type.

Читайте также:  Installing rpm files linux

The environment variable PS1 (Prompt String 1), is used for the interactive shell prompts, which sets the Bash prompt. A PS2 variable is also used when more input is required to complete a Bash command.

Yes, while prompting for user input, you can provide a default value. Even if you recommend a default value to the user, you can allow them to override it if they so desire.

Источник

How do I read user input into a variable in Bash?

You should also quote your variables to prevent pathname expansion and word splitting with spaces:

# passwd "$user" # mkdir "$home" # chown "$user:$group" "$home" 

Can you show how to write that "Continue? (Y/N)" line in multiple lines for readability? I'm attempting to, and this doesn't seem to work: if [[ "$confirm" == [yY] ]]; do .

I should have used then not do : if [[ "$confirm" == [yY] || "$confirm" == [yY][eE][sS] ]]; then . anyway, if you add this multi-line version to your answer it would be helpful.

I used read -p "Is this OK? (y/n)" confirm && if [[ ! "$confirm" =~ ^[Yy]+([eE][sS])?$ ]]; then echo "it's not yes"; fi this matches yyyyyyyy yyyyyyes but not yessssss , yeeees , yep or N , etc

Yep, you'll want to do something like this:

echo -n "Enter Fullname: " read fullname 

Another option would be to have them supply this information on the command line. Getopts is your best bet there.

#/bin/bash read -p "Enter a word: " word echo "You entered $word" 

Maximally portable (bash, zsh, . ):

printf "%s" "Enter fullname: " read fullname 

This is the most portable way to read with prompt. Methods such as read -p and echo -n are more likely to fail depending on the shell.

user=$(zenity --entry --text 'Please enter the username:') || exit 1 

One line is read from the standard input, or from the file descriptor fd supplied as an argument to the -u option, split into words as described above in Word Splitting, and the first word is assigned to the first name, the second word to the second name, and so on. If there are more words than names, the remaining words and their intervening delimiters are assigned to the last name.

echo "bash is awesome." | (read var1 var2; echo -e "Var1: $var1 \nVar2: $var2") 

bash will be var1
is awesome will be var2
echo -e enable interpretation of backslash escapes from ubuntu manual.

echo -n "Enter Fullname: " read fullname echo "your full name is $fullname." echo -n "test type more than 2 word: " read var1 var2; echo -e read var1 var2; echo -e "Var1: $var1 \nVar2: $var2") 

Источник

Linux bash user input

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью
Adblock
detector