How to get user input in Bash shell script?

Getting Runtime Input values with “read” command in Bash shell scripting:

We can create a shell script by using the static and dynamic method. As we all know in the static method it will not take the runtime input values, every time you run the static script it displays the same output. dynamic scripting is different from static as it takes the runtime input values.😊

To get the run time inputs:

To get the user inputs we use the inbuilt shell command “read”, what it actuallky does is it takes the input values and save it inside the variable.

The syntax for read command:

#read  <variable name>

Let us look at a simple example script

#vi  /myscript.sh

#!/bin/bash

    #Ask the user for their name

     echo  Hi, MAy I know who is this?

     read myvar

     echo "Welcome to Vasanth blog  $myvar

     :wq

 

Line 1: Defining the Interpreter

Line2: Comment field

Line3: Display a message asking the user for input

Line4: To get the input from the user and save it in the variable "myvar"

Line5: Display another message to confirm read command executed successfully
“read” command with options:

We can use the “read” commmad with a variety of  command line options . There are two commonly used options  are p, which allows you to specify a prompt message on your console, and -s which makes the input hide  i.e will not display the  given input on the console. I will show you one example of how we can apply these two options to ask user name and password.

-p = Prompts a message

-s =To hide the inputs
#vi  /demo.sh

#!/bin/bash

#Ask the user for login details

read  -p  "Username:   "  var1

read  -ps  "Password   "  var2

echo "Thank you  $var1 your authentication is success"

:wq!

Line3&Line4:  we added the prompt with quotes so that we can have a space included with it, otherwise  the user input will straight after the; last character  of the prompt

As you can see from the above output the last line i.e the prompt message is added with the password line, To print the prompt message at the new line you can add the “echo” command without any argument as shown below,  This is a good way to get a blank line on the screen to help space things out.

#vi  /demo.sh

#!/bin/bash

#Ask the user for login details

read  -p  "Username:   "  var1

read  -ps  "Password   "  var2

echo 

echo  "Thank you  $var1 your authentication is success"

:wq

Let us see another example with more inputs,
#vi /script.sh

 #!/bin/bash 

echo "Which sports do you like?"

 read   sp1 sp2 sp3 

echo "Your first sport was:  " $sp1 

echo "Your first sport was:  " $sp2

 echo "Your first sport was:  " $sp3 

:wq!

Let as run this script as shown below

#./script.sh

The read command first it will take your input and spilt it on white space. The first input will  then be assigned  to the first variable name, the second input to the second variable name and so on it continues..👨‍💻

I hope you have enjoyed this tutorial if so Kindly subscribe and share it with your friends.
                                          🙏🙏 Thank you 🙏🙏
#############################################################
For More Videos Subscribe My Youtube Channel    https://youtu.be/A7a72pmPa5o
If you found this article useful, Kindly Subscribe here 👉  Click this link to Subscribe
Never miss an article Do like my official  FB page 👉 Learn Linux in an easier way

#############################################################################################

Learn how to create a Static and Dynamic Bash Shell Script file

In this article, we will learn how to create a shell script by using the following methods

1.Static Shell script

2)Dynamic shell script

Static shell script: In static scripting, you can execute any no.of times and it generates the same output i.e it is not taking the runtime input values while executing your script.

Dynamic Shell script: It always takes the runtime input values, based on the different sets of input values it will generate different outputs.

Let us create one basic monitoring script by using the static method

Ex:1 Create a script to monitor your server performance

Method: Static

#vi   /myscript.sh

#!/bin/bash

echo "Display the Memory usage details"

echo "***********************************"

free  -m

echo "Display the Server Load average and run time details"

echo "************************************"

uptime

echo "Display the  Cpu activity and RAM Details"

echo "**************************************"

cat  /proc/meminfo

echo "***************************************"

:wq!

Now Add the Execute permission

#chmod u+x   /myscript.sh

Run the script as follows

#./myscript.sh  or sh  /myscript.sh

Once you execute the script the interpreter reads each and every line from the file and displays the output on the console.

Sample Output:👇🏿👇🏿

The main advantage of using the shell programming is automatically it executes all your larger tasks, you can combine multiple commands in a single file that are required to monitor your server performance and by adding the execute permission you can run the script file as a program.

Ex:2  Display the Total Number of Lines in a file

Method: Static

when I run a script it should display the total number of lines in a file. As all we know in Linux we have many commands to get this from the command line arguments, the same task if I put it inside the script file how it works🤗

let us create the  script file as follows

#vi  /demo.sh

#!/bin/bash

echo "Display the Total Number of Lines in a file"

cat  /var/log/messages    |wc  -l

echo "End Of Script"

:wq!

Sample Output:👇🏿👇🏿

As you can see from the above output the file has a total number of 68 lines.

Ex:3  Create a script that tells the username and prints the running process

#vi  /test.sh

#!/bin/bash

echo   "Hello,$USER

echo  "Hey, I am " $USER " and I will show you the current running process details"

echo "Display the Running processes details"

ps

:wq!

Sample Output:👇🏿👇🏿

As you can see from the above output the ps displays the running processes details from your current terminal

Note: To display all the running processes from all the terminal you must have to use the option -aux with the ps command.

Ex:4 Create a script to get the runtime input values from the keyboard(Dynamic Method)

In shells scripting, we use the command “read” to get the inputs from the keyboard, the read command  what this does is wait for the user to type something followed by the enter key it  stores that given input to the variable

Let me create a simple script to get the inputs from  by using the read command

#vi  /dynamic.sh

#!/bin/bash

echo "Hi there, What is your First Name?"

read var1

echo "Welcome Mr/Mrs. $var1, Would you like to tell us the last name?"

read var2

echo "Thanks, Mr/Mrs. $a $b for telling us your name"

echo "*********************************"

echo "Mr/Mrs, $b its time to say goodbye"

:wq!

Sample Output:👇🏿👇🏿

Ex:5 Get the inputs from the keyboard

#vi  /script.sh

#!/bin/bash

echo "Please type your name"

read  data

echo "Hi $data, Let us be friends"

:wq!

As you can see from the above output, read command takes the input which is assigned from the keyboard and then it stored the value inside the variable “data”, the last line prints the value we assigned ..  next time again run the same script, give another input you will get different output this is why it is called as the dynamic scripting(i.e It always takes the runtime input values)

In our next article, I will share you more programs by using the “read command”.

Your Valuable “thoughts” in comments is highly appreciated, please do Like and share us to spread.

If you found this article useful, Kindly Subscribe here 👉  Click this link to Subscribe

Never miss an article Do like my official  FB page 👉 Learn Linux in an easier way

For More videos Subscribe My Youtube Channel 👉🏻https://www.youtube.com/channel/UC6bR8In-jj9-klVlZQ6YH_A

 

Follow me at twitter @linuxvasanth

 

 

Quotes in Bash Shell Scripting

Quoting

Enclosing the command or text with the quotation is a standard practice on the Linux command prompt mostly when you are assigning the values with space, or with some special character .but how to know whether you want to use ‘single quotes’ or “double quotes”?Let me explain this difference

The common rule is You can prevent the shell from substituting the value of a variable by quoting (single quotes), whereas double quotation mark do not prevent the substitution.

Quotes with text

When you are assigning a  few words of text it really doesn’t a matter whether you use, since they both will work exactly the same. Let me show this with one simple example

To Learn the basics of bash shell scripting click this link 👉🏻  http://www.linuxvasanth.com/bash-shell-scripting/

The below two commands will create a file test file.

#touch  'test file'

#touch  "test file"

Bash Shell Variable Expansion:

When you are working with a variable name in the command line the single quotes and double quotes behave very differently.

#myvar="abc is a single string"

#echo $myvar

Sample Output: abc is a single string

Now when you are using the single quotes it prevents substitute the values from the variable

#echo '$myvar'

Sample Output: $myvar

From the above output, it displays only the variable name when you are using with single quotes and double quotation mark do not prevent the substitution.

Note: Single quotes will treat every character Literally i.e Strictly follows the exact word, Double quotes will allow you to do the substitution i.e includes variables within the setting of the value.

Note: Double quotation marks are useful when you assign a value to variables, To assign a value that contains spaces or tabs to a variable, use double quotation marks around the value.

If you found this article useful, Kindly Subscribe here 👉  Click this link to Subscribe

Never miss an article Do like my official  FB page 👉 Learn Linux in an easier way

How to create and assign values to variables in Bash shell scripting?

What is VARIABLE?

A Variable is a character string to which we assign a value. The value could be a number, filename or any other type of data. Simply we can say a variable is a pointer to a particular value or data. By default Shell allows us to do create, modify, delete the variables, remember these variables are only a temporary one🙄 i.e when you close the session, by default these variables get deleted🤨. So if you want to make a variable and its value permanent i.e to make it as a system-wide you should export the variable or updated it in to the environmental variable.

What is Valid  and invalid variable names?

You should always remember a variable name must start with a letter or underscore, but not with a number.

For example, a valid variable name would look like this👇🏿👇🏿

1.A76 

2.my_cat 

3. _hello_

 

An invalid variable name look like this👇🏿👇🏿

1.69_street

2.my-name

If you use a hyphen(-) or u start a variable with numbers then those are considered to be as the invalid variable names.

Types of Variables

There are two types of variables exists in bash shell scripting

1.Local variable

2.Environmental variable

What is Local variable?

Local variables are the variable that is contained exclusively within the shell in which they were set or defined. i.e once you close the terminal or session the information will get erased from the memory.

What is Environmental variable?

E.v are the variables that are defined for the current shell and are inherited by any child shell or processes i.e it updates a value system-wide if you want to make a variable value permanent you should update it in an environmental variable.

Note: To export a value systemwide you will need to open the following file /root/.bashrc and update the variable and its values.

How to assign a value to a variable in bash shell script?

Assigning a value to a variable in bash shell script is quite easy🤠, use the following syntax to create a variable and assign a value to it.

syntax

#variablename=value

Ex:1 Create a variable and assign a value to it

Let me create a variable with the name myvar and assign a value ABC to it.

#myvar=ABC

How do I display the values from the variable?

Use the following syntax to display the values from a variable

Syntax:

#echo  $variablename

Ex:2 To display the value from the variable called “myvar”

#echo  $myvar

Sample output: ABC
Note: If you skip the $ sign then it would display  only the variable name “myvar”, the shell will not execute the values from the variable
Note: “echo” command which is used to read the values from the variable.

 

Ex:3 Let us create a shell script to display the total no.of lines in a file

Method: Static

#vi  /demo.sh 

       #!/bin/bash 

       echo "Display the total number of lines in a file"

       cat  /var/log/messages  |wc  -l 

      echo  "End of Script" 

      :wq!

 

Explanation:

Line:1  Define the interpreter(bash is the interpreter here)

Line:2 Prompt a message on the screen

Line:3 The command to display the no of lines in /var/log/messages file

Line:4 After displaying the output it prints end of script  message on the screen

Note: Since I have created the above script by using the static method, whenever I run this script it displays the same output.

               In our next article, I will be explaining about the “quotes” in bash shell scripting

**************************************************************************************************************************************

If you found this article useful, Kindly Subscribe here 👉  Click this link to Subscribe

Never miss an article Do like my official  FB page 👉 Learn Linux in an easier way

***************************************************************************************************************************************

What is Bash Shell Scripting?

Introduction

As we all know Shells are interactive i.e it accepts the inputs from the keyboard given by a user and  execute them ,Suppose if you have a routine task and that task is having some 20 to 30 Unix commands then it would be difficult for the administrator to execute each and every command one by one to create a report, to ease the administrator task we put all the Required commands in a text file and tell the user to execute them this is called as a shell script

A script could be written to start a database, shut down a database, start a backup program check whether a specific service is up and if not it could start it, so many other tasks can be done using the shell scripts.

NOTE: Writing shell scripts halt automates the administration tasks saves the admin time etc..

Advantages of having Shell Scripting:

1.Ease of use: If you have to run a sequence of commands in your daily task then it is easier to have a shell script file to do them. All you have to do is just execute the file to run the several commands.

2.Easier to Remember: If you are using man arguments and options it is quite easy to miss command options or arguments if you are typing it every time into the command line.

Procedure to create a Shell script file:

1. Create a file with the required commands or codes as per the requirements.

2. The command or code to be run by some interpreter so Add the interpreter in to the script file(here we use “bash” as the interpreter).

3. Add the commands or codes in to the script file

4. Add the execute permission to the script file

5.Run the script file

These all are the steps you need to follow to create a proper shell script file.

Ex:1 Create a basic Monitoring Shell script file

In this example, I will create a script file which is to monitor the server health performance and resources usages.

Step:1

#vi   /script.sh

#!/bin/bash

free - m

who

last |grep reboot

who -r

netstat  -l

netstat -s

cat  /var/log/messages   |wc  -l

:wq!

Step:2 Add the execute permission to the user(here as a root I will execute the script file)

#chmod   u+x   /script.sh

#ls  -l   /script.sh

Step:3 Run the script file

Syntax:  #./scriptfilename

#./script.sh

Note: For better view Output has Truncated🖕🏻

As you can see from the above output the interpreter will read and execute each and every command inside the file and prints the output on the screen.

Note: Here  “.” indicates run the script from your current path, if the script is not in your current path then you will get the message No such file or directory.

I hope you have enjoyed this article…

If you found this article useful, Kindly Subscribe here 👉  Click this link to Subscribe

Never miss an article Do like my official  FB page 👉 Learn Linux in an easier way