How to use Command Line Arguments in Bash

Here's how to receive user input in a Bash script on Linux.

1. Using read to receive user input

You can receive user input and store it in a variable named name by using the following command. This will display a prompt message for the user to enter their input on the next line.

#!/bin/bash

echo "Enter the user name: "
read name
echo "name: $name"

Output:

$ bash example.sh
Enter the user name:
Jisung
name: Jisung

2. Receiving Multiple User Inputs

The previous example received one input from the user. To receive two or more inputs, you can use multiple variables with the read command. The user's input will be stored in the variables sequentially.

#!/bin/bash

echo "Enter the user name and email: "  
read name email
echo "name: $name, email: $email"

Output:

$ bash example.sh
Enter the user name and email:
Jisung js@codechacha.com
name: Jisung, email: js@codechacha.com

3. Receiving Input on the Same Line as the Prompt

To receive user input on the same line as the prompt message, you can use the -p option with the read command. If you use the format read -p "MESSAGE" VARIABLE, the message will be displayed and the user can input their response on the same line.

#!/bin/bash
read -p "Enter the name: " name
echo "name is $name"

Output:

$ bash example.sh
Enter the name: Jisung
name is Jisung

4. Hide User Input in Terminal

Sometimes when receiving input from the user, there is information like passwords that should not be displayed on the screen. You can add the -s option to hide the user input on the screen.

#!/bin/bash

read -p "id : " id
read -sp "pw : " pw

echo
echo "name is $id"
echo "pw is $pw"

Output:

$ bash example.sh
id : js
pw :
name is js
pw is 1234

5. Receiving Variable User Input

The -a option is used to receive user input as an array. When the user enters 3 items, the size of the array will be 3, and if they enter 2 items, the size of the array will be 2. ${#names[*]} represents the length of the array.

#!/bin/bash

echo "Enter names"
read -a names

echo "Input size: ${#names[*]}"

echo "first: ${names[0]}, second: ${names[1]}, third: ${names[2]}"

Output:

$ bash example.sh
Enter names
AA BB CC
Input size: 3
first: AA, second: BB, third: CC

5.1 Looping through variable input with a loop

You can process variable user input using a for loop. ${names[*]} represents all the data in an array, and you can iterate through all the data using a loop.

#!/bin/bash

echo "Enter names"
read -a names

echo "Input size: ${#names[*]}"

for name in "${names[*]}"
do
  echo "name: $name"
  echo
done

Output:

$ bash example.sh
Enter names
AA BB CC
Input size: 3
name: AA BB CC
codechachaCopyright ©2019 codechacha