Shell Scripting | Creating Scripts Using Variables

bash shell scripting learn with examples

Please Read This 👇🏾

 

In previous post, we had learnt , how variables are defined in bash shell scripting. Now in this post we will see some real world examples of shell scripting using variables.

Example 1: It is simple self introduction script with defined variables





Explanation:

1) lines 5,6,7,8 : defined variables intro, Name, Company, Study in which we puts simple strings of characters.

Note that for simple character , numbers string,  we only have to quotes ( "" ) the string

2) lines 9,10,11,12 : executing the echo commands with our defined variables:

Note that when ever we assign a command in a variable we put command in () braces with dollar $ sign.

3)  Save file as with .sh extension & give execution permissions. run with absolute/relative path.

bash shell scripting
simple variable script

Example 2: It is simple system info and  connectivity check status script with  defined variables



 Script Explanation:

1) Skipping 1 to 5 lines in our script as we already discussed these lines.

2) line 6 : set -e  is a special command in bash script which will tell the system if there is any error in our script and it will stop the execution of our commands and exit.

3) line 7: a user variable is defined which will print the current login user name. 

4) line 8 : a system_details variable is defined which will print the system details along with host-name and ip address

5) line 9 : a connectivity variable is defined which will ping the google.com in order to check the network connectivity.

Note that when ever we assign a command in a variable we put command in () braces with dollar $ sign.

6) line 10 ,12,15 : These are simple echo commands which will prints the message typed in between  quotes " " sign. where -e option is expressions for print a message in a new line (\n

7) line 11,13,16 : Displaying the output of our variables.

Note that when we want to use variable in our script we have to use echo for simple execution. put variable inside {} braces  with dollar sign. 

8) line 17: Its optional , but important to display the message that our script is executed successfully.

9) Now save the script & give execution permissions to it and then run the script via absolute path or relative path ( ./script_name )

OUTPUT:


bash programming variable examples
output

Create Some More Scripts Using Variables e.g system hostname details, mount partitions details etc.


Share This Post With Your Friends 😀


Previous                                                                                                                                           Next     

Post a Comment

0 Comments