Articles

Home / Articles / DevOps / How to take input in a Bash script?

How to take input in a Bash script?

Published on Oct. 22, 2021

In order to make our script interactive and dynamic, we need to take some input from the user. By taking the input we can actually provide some details to our script while running that into your system. This could help the user to perform some dynamic tasks at the time of execution of the script.

 

In this article, we are going to know how we can take input in a bash script. In case, you don't have knowledge about the bash script you can follow this page - How to create a simple Bash script?

 

Table of Content

 

How to pass a single input?

To pass a single input to a script here is the script - 

 

#!/usr/bin/bash
var1=$1
echo "Hello $var1"

 

In the above code, var1 will get the value from the first position while running the script. To pass the input we can follow the command

 

bash <file-name> <value-of-variable>

 

for e.g. I have saved the above script with the name test.sh. 

 

bash test.sh BrighterBees

 

How to pass multi inputs?

Bash script has the capability to pass multiple inputs by space-separated. The syntax is like - 

 

#!/usr/bin/bash
var1=$1
var1=$2
var1=$3
echo "Hello $var1"
echo "Hello $var2"
echo "Hello $var3"

 

While running the above script pass the variables in the following manner -

 

bash <file-name> <first> <second> <third>

 

For e.g.

 

bash test.sh Ram Akash Jack

 

Output

 

Hello Ram
Hello Akash
Hello Jack

 

How to pass dynamic inputs?

We want to make our script as dynamic as we can. There might be a chance the number of inputs may vary from client to client. They will have the freedom to provide that to this script as per their requirement. For this problem, we want a setup where we can take input dynamically.

 

#!/usr/bin/bash
var=$@
echo "Hello $var"

 

The above script will be able to get any number of inputs you want. 

 

How to prompt for input?

We have the following Linux command to take input by prompting the user

 

read x

 

We can use that in our script as well

 

#!/usr/bin/bash
echo -n "Enter a variable: "
read var
echo "Hello $var"

 

Final Voice

In this article, we have discussed how we can take input and pass that to our script. In case you want to learn more about bash scripting bookmark this website.

 

Connect with the Author on Twitter

 

···