bash scripting Archives - The Linux GURUS https://thelinuxgurus.com/tag/bash-scripting/ Learn Linux & DevOPS from THE LINUX GURUS Fri, 13 Mar 2020 04:23:37 +0000 en-US hourly 1 https://i0.wp.com/thelinuxgurus.com/wp-content/uploads/2020/01/cropped-thelinuxgurus_transparent_name.png?fit=32%2C32&ssl=1 bash scripting Archives - The Linux GURUS https://thelinuxgurus.com/tag/bash-scripting/ 32 32 148921671 Introduction to Bash Scripting Tutorial https://thelinuxgurus.com/introduction-to-bash-scripting-tutorial/ https://thelinuxgurus.com/introduction-to-bash-scripting-tutorial/#respond Fri, 13 Mar 2020 04:25:58 +0000 https://thelinuxgurus.com/?p=957 Linux Shell Scripting is & always has been one of the most desired skills that a System Administrator and now DevOps engineers are required to...

The post Introduction to Bash Scripting Tutorial appeared first on The Linux GURUS.

]]>
Linux Shell Scripting is & always has been one of the most desired skills that a System Administrator and now DevOps engineers are required to have. It has been used by Linux experts to perform all sorts of tasks, especially repetitive tasks or for automating tasks.

Consider this post as the central reference point for all Scripting tutorials published here at The Linux GURUS. This scripting tutorial just provides a brief about scripting & why we require it. Mentioned below is list of all the tutorials to get yourself started with & master it.

Bash Scripting tutorial

1- Scripting – Understanding Linux Environment variables – In this scripting tutorial, we will learn about Linux shell variables or Environment variables. We will learn their types, how to create them, check them.

2- Bash Scripting – using variables in Linux shell scripts – In this tutorial, we will learn to the variables in bash scripts. We have discussed examples for using local variables, global variables & also command substitution variables.

3- Bash scripting – performing arithmetic operation in shell script – In this tutorial, we have discussed various arithmetic operations as well about logical/boolean operations as well.

4- Bash Scripting- Using conditionals (if else in shell script)- Here we have discussed how we to use the conditional statements in bash script. We discussed about if-else, if-then-else, multiple if statements & about elif statements.

5- Bash Scripting- Performing file, string comparisons & numeric comparisons in Bash- In this tutorial, we have discussed how we can perform file, numeric & string comparisons.

6- Bash Scripting- Using Logical operators in shell scripts:- In this tutorial, we have discussed some advanced concepts for performing mathematical, string comparison as well as using logical operators.

7- Scripting- Using FOR loops in shell script- In this tutorial, we have discussed about FOR loop in a shell script.

8- Bash Scripting- Taking user input using Read command in shell script- Here we discuss how we can take input from users & assign as a value for variable to be used in shell script.

9- Bash Scripting- Using until & while loop in shell script- Here we have discussed use of more loops i.e. while & until loops.

10- Bash Scripting- Controlling Loops using Continue & Break in shell script- In this tutorial, we have discussed how we control loops in out shell scripts using continue & break commands.

11- Bash Scripting- Input output redirection in Linux- Learn how to redirect the input & output in Linux with this tutorial.

12- Bash Scripting- Creating Shell Script Functions- Learn how to create functions for bash scripts as well also learn about creating local variables in this tutorial.

This is our completes our tutorial, we will be adding more scripting tutorials in future & will also update about those in this tutorial. If you have any suggestions, or queries about this scripting tutorial or any other tutorial, you can connect to us using the comment box below.

If you think we have helped you or just want to support us, please consider these:-

Connect to us: Facebook | Twitter | Linkedin

TheLinuxGURUS are thankful for your continued support.

The post Introduction to Bash Scripting Tutorial appeared first on The Linux GURUS.

]]>
https://thelinuxgurus.com/introduction-to-bash-scripting-tutorial/feed/ 0 957
Bash scripting – Understanding Linux Environment variables https://thelinuxgurus.com/bash-scripting-understanding-linux-environment-variables/ https://thelinuxgurus.com/bash-scripting-understanding-linux-environment-variables/#respond Mon, 13 Jan 2020 09:25:41 +0000 https://thelinuxgurus.com/?p=954 Linux Environment variables are variables that store the information for the shell environment & the shell sessions. These variables are accessed by any scripts or...

The post Bash scripting – Understanding Linux Environment variables appeared first on The Linux GURUS.

]]>
Linux Environment variables are variables that store the information for the shell environment & the shell sessions. These variables are accessed by any scripts or Linux program to get a frequently accessed value.

We have discussed briefly Linux Environment variables, but what exactly is a variable. Most of you might know, but for those who don’t, a variable is used for storing some information like a string or a number or file location. When a variable is referenced in a program or shell script, basically it is requesting the stored value for those variables. Variables allow us to store some frequently accessed data so that we don’t have to write it again and again.

Recommended Read: Important PostgreSQL commands that every beginner should know

Also Read: Bash Scripting-2- Using VARIABLES in Linux shell scripts

Now back to the Linux Environment variable, as mentioned above we also reference them as environment variables. These can be of two types:-

1- Local Variables: These variables are created for a single shell session & are only available until a session is running. Once a session ends, we can’t use them again, these variables are only available for the terminal where they were set & can’t be used on other terminals.

2- Global variables: These are system-wide Linux Environment variables & are available to be used for all shells, terminals & sessions.

Important Linux Environment variables commands

1- Create a local Linux environment variable

To create a local variable, use the following command,

# new_varaiable_name=”test value”

Use this without any spaces.

2- Create an global Linux environment variable

To create a global environment variable, first, create a local variable & then export it,

# new_varaiable_name=”test value”

# export new_varaiable_name

3- To check the list of all Linux Environment variables, use the following command,

# set

4- To get value of only a single variable,

# printenv variable_name

5- Unset an environment variable

To remove a variable from the list of environment variables, we can run the following command,

# unset variable_name

6- using PATH command

PATH command is another important command that we might use, it is basically used to save path for either a program or script. We can set the path a script & next time when we need to execute the script, we need not use the full path & can only run the script directly,

To set the path, use

# PATH=$PATH:/home/test-user/testing.sh

Now to run the script, only have to run

# testing.sh

& the script will run, irrespective of whichever directory we are in. We can also set the path for a directory that might contain the scripts & this will also work the same way,

# PATH=$PATH:/home/test-user

That’s it for our tutorial on Linux Environment Variables. Please feel free to send in any questions or queries using the comment box below.

If you think we have helped you or just want to support us, please consider these:-

Connect to us: Facebook | Twitter | Linkedin

TheLinuxGURUS are thankful for your continued support.

The post Bash scripting – Understanding Linux Environment variables appeared first on The Linux GURUS.

]]>
https://thelinuxgurus.com/bash-scripting-understanding-linux-environment-variables/feed/ 0 954
Bash Scripting-2- Using VARIABLES in Linux shell scripts https://thelinuxgurus.com/bash-scripting-2-using-variables-in-linux-shell-scripts/ https://thelinuxgurus.com/bash-scripting-2-using-variables-in-linux-shell-scripts/#respond Mon, 13 Jan 2020 09:17:40 +0000 https://thelinuxgurus.com/?p=951 In this tutorial, we will learn more about using variables in Linux & will also create some simple bash scripts utilizing global environment variables &...

The post Bash Scripting-2- Using VARIABLES in Linux shell scripts appeared first on The Linux GURUS.

]]>
In this tutorial, we will learn more about using variables in Linux & will also create some simple bash scripts utilizing global environment variables & local variables. As mentioned in our earlier tutorial, we can create a local variable the following way,

# new_variable=”test-value”

Example:

# school=’THE LINUX GURUS’

Recommended Read: How to setup SSH login without password on Linux systems

Also Read: Bash scripting – 3 – Performing Arithmetic Operation in shell script

Using local Variables in Linux

Now let’s create a simple script utilizing this and another local variable,

#!/bin/bash

NAME=”Prince DAN”

SCHOOL=”THE LINUX GURUS”

echo $NAME

echo $SCHOOL

echo “My name is $NAME & i am a teacher at $SCHOOL”

Save the script & close the editor. Now before we execute this script, please read the following points,

1- ‘#1/bin/bash’ is called as shebang & it tells the interpreter that following lines are written & to be executed in bash,

2- To call or to use variables in the script, we use ‘$’ followed by the name of variables,

3- lastly we need to provide the execute permissions to the script to run it. Use the following command to provide the rights,

# chmod +x simple_script.sh

Now that we have to execute the script, & the output will be,

# sh simple_script.sh

Prince DAN

THE LINUX GURUS

My name is Prince DAN & i am a teacher at THE LINUX GURUS

Using global variables in scripts

So we already have some environment variables setup by default on all the Linux machines. Some of these variables are, UID, USER, HOME (you can get complete list with the ‘set’ command). Now let’s utilized these variables,

# vi simple_script_2.sh

Create the following script,

#!/bin/bash

echo “ Current user is : $USER “

echo “ $USER has $UID UID”

echo “ & his home path is $HOME”

Save the file & execute the script, output will be,

# ./Simple_script_2.sh

Current user is: test-user

test-user has 453 UID

& his home is /home/test-user

Notice that we have not declared the values for mentioned variables in our script & values are being captured from the environment variables.

Using command substitution in variables

Command substitution is another way we can utilize variables, so with command substitution we will assign the output of a command as the value for a variable,

# new_date=$(date +%y%m%d)

echo $new_date

The same can be utilized in the scripts as well. This is all for now on using variables in Linux.We will discuss more about bash scripting in our coming tutorials, please feel free to share the tutorial or send in any questions or queries using the comment box below.

If you think we have helped you or just want to support us, please consider these:-

Connect to us: Facebook | Twitter | Linkedin

TheLinuxGURUS are thankful for your continued support.

The post Bash Scripting-2- Using VARIABLES in Linux shell scripts appeared first on The Linux GURUS.

]]>
https://thelinuxgurus.com/bash-scripting-2-using-variables-in-linux-shell-scripts/feed/ 0 951
Bash scripting – 3 – Performing Arithmetic Operation in shell script https://thelinuxgurus.com/bash-scripting-3-performing-arithmetic-operation-in-shell-script/ https://thelinuxgurus.com/bash-scripting-3-performing-arithmetic-operation-in-shell-script/#respond Mon, 13 Jan 2020 09:07:48 +0000 https://thelinuxgurus.com/?p=948 In this tutorial, we will learn about performing arithmetic operations in shell scripts & also about the logical/boolean operators. So let’s first start with the...

The post Bash scripting – 3 – Performing Arithmetic Operation in shell script appeared first on The Linux GURUS.

]]>
In this tutorial, we will learn about performing arithmetic operations in shell scripts & also about the logical/boolean operators. So let’s first start with the all the arithmetic operations as well as the arithmetic, boolean operators that can be used in Linux,

Recommended Read: How to install MySQL on Ubuntu

Also Read: Bash Scripting-4- Using conditionals (if else in shell script)

Arithmetic Operators

Logical and Boolean Operators

+

Addition

<=

less than or equal to

substraction

>=

greater than or equal to

++

Increment

<

less than

Decrement

>

greater than

*

Multiplication

==

Equal to

/

Division

!=

not equal to

%

Remainder

!

logical NOT

**

Expornention

&&

logical AND

||

logical OR

Now let’s see some examples of performing arithmetic operation in shell script,

Addition & Subtraction

#!/bin/bash

num1=10

num2=20

num3=40

echo “ Adding $num1 & $num2, output is $[$num1+$num2]”

echo “Subtracting $num2 from $num3, the output is $[$num3-$num2]”

Multiplication & Division

#!/bin/bash

num1=10

num2=20

num3=40

echo “ Multipying $num1 & $num2, output is $[$num1*$num2]”

echo “Dividing $num2 by $num3, the output is $[$num3/$num2]”

Performing a Floating point arithmetic operations in shell script

Now when we perform some arithmetic operations like division, we might get the answer as floating point number. For example,

#!/bin/bash

num1=5

num2=2

echo “Dividing $num1 by $num2, the output is $[$num1/$num2]”

So the output, in this case, would be ‘2.5’ but we would get the output as ‘2’. So how to work this out, how to get the right answer. To accomplish this floating point arithmetic operation, we need to use ‘bc’ command.

bc command or bash calculator which allows us to perform floating point arithmetic operations. Syntax for using the bc command is,

# “scale=3; num1/num2 | bc

Here scale=3 means the number of decimal places up to which division will be performed. So the above mentioned script will change to,

#!/bin/bash

num1=5

num2=2

echo “Dividing $num1 by $num2, the output is $(echo “scale=3; $num1/$num2″|bc) “

Now the output for the script will be,

Dividing 5 by 2, the output is 2.500

So with this, we will end this tutorial on performing Arithmetic Operation in shell script. These bash scripting tutorials will continue with our coming posts as well. Please do send us your suggestions, questions or queries using the comment box below.

If you think we have helped you or just want to support us, please consider these:-

Connect to us: Facebook | Twitter | Linkedin

TheLinuxGURUS are thankful for your continued support.

The post Bash scripting – 3 – Performing Arithmetic Operation in shell script appeared first on The Linux GURUS.

]]>
https://thelinuxgurus.com/bash-scripting-3-performing-arithmetic-operation-in-shell-script/feed/ 0 948
Bash Scripting-4- Using conditionals (if else in shell script) https://thelinuxgurus.com/bash-scripting-4-using-conditionals-if-else-in-shell-script/ https://thelinuxgurus.com/bash-scripting-4-using-conditionals-if-else-in-shell-script/#respond Mon, 13 Jan 2020 08:00:26 +0000 https://thelinuxgurus.com/?p=945 Up until now, we have discussed using environment variables, using local & global variables & also about performing arithmetic operations in bash. Now we are...

The post Bash Scripting-4- Using conditionals (if else in shell script) appeared first on The Linux GURUS.

]]>
Up until now, we have discussed using environment variables, using local & global variables & also about performing arithmetic operations in bash. Now we are ready to discuss some advanced stuff, we will discuss how to use if else in bash script & also other conditional statements.

Recommended Read: Examples on how to use RPM command in Linux

Also Read: Bash Scripting- 5 – Performing FILE, STRING comparisons & NUMERIC comparisons in Bash

If-then, else, elif are all called conditional statements. A conditional statement is used when we are required to satisfy a condition first, then execute a single or number of other commands. So we will be discussing all of these with the help of some examples. Let’s start with if-then statement,

Using if then statement in bash script

Syntax

If linux_command

then

              some_other_linux_commands

fi

As syntax shows, when the first command mentioned after ‘if’ works, then only the command after ‘then’ condition will work. Let’s see a simple script,

Example:

#!/bin/bash

If top

then

              echo “Script works”

fi

Here we have only use a single command, but we can use a number commands as well.

Another example,

#!/bin/bash

user=”ec2-user”

if grep $user /etc/passwd

then

              echo “user exists”

              echo “contents of his home directory are”

              ls -a /home/$user

fi

Here, we have created a variable for user & we are then checking if the user exists in ‘/etc/password’. If the user exists, then it will echo the same & will then display the contents of its home directory.

Using if else in shell script

Until now, we were presuming that the outcome of the condition will be positive but if that is not the case. So we use if then else statement to have an outcome for both conditions.

Syntax

If linux_command

then

              some_other_linux_commands

else

              some_other_linux_commands

fi

Let’s see an example,

#!/bin/bash

user=”ec2-user”

if grep $user /etc/passwd

then

              echo “user exists”

              echo “contents of his home directory are”

              ls -a /home/$user

else

              echo “User does not exist”

fi

The script is simple, first, it will look for a user & if the user exist, then it will show the user’s home directory content, else will print “user does not exist”. Now let’s see another example, where we will use multiple if statements,

#!/bin/bash

user=”ec2-user”

if grep $user /etc/passwd

then

              echo “user exists”

              echo “contents of his home directory are”

              ls -a /home/$user

else

              echo “User does not exist”

              if ls –a /home/$user

              then

                            echo “But the user has a directory”

              fi

fi

The script is the improvised version of the above-mentioed script, it will look for a user & if the user exists, then it will show the user’s home directory content, else will print “user does not exist” & then it will also look if there is a home directory for the mentioned user.

Using if-elif-else in bash script

Another method for using multiple if statements is by using elif command. Its especially useful, when you are writing long scripts when it might become difficult to keep track of conditional statements. Let’s have a look at an example,

#!/bin/bash

user1=”ec2-user”

user2=”root”

if grep $user1 /etc/passwd

then

              echo “user exists”

              echo “contents of his home directory are”

              ls -a /home/$user

elif

              if grep $user2 /etc/passwd

              then

                            echo “user exists”

                            echo “contents of his home directory are”

                            ls -a /home/$user

else

              echo “User does not exist”

fi

Here we have changed the above-mentioed script to look for two users with the help of elif statements. We can also use multiple elif statements like other statements.

All these were some very basic examples of using if else in shell script. We will be discussing some other examples in future tutorials. So we now end this tutorial on using if else in shell script, please feel free to send any questions, queries or suggestions using the comment box below.

If you think we have helped you or just want to support us, please consider these:-

Connect to us: Facebook | Twitter | Linkedin

TheLinuxGURUS are thankful for your continued support.

The post Bash Scripting-4- Using conditionals (if else in shell script) appeared first on The Linux GURUS.

]]>
https://thelinuxgurus.com/bash-scripting-4-using-conditionals-if-else-in-shell-script/feed/ 0 945
Bash Scripting- 5 – Performing FILE, STRING comparisons & NUMERIC comparisons in Bash https://thelinuxgurus.com/bash-scripting-5-performing-file-string-comparisons-numeric-comparisons-in-bash/ https://thelinuxgurus.com/bash-scripting-5-performing-file-string-comparisons-numeric-comparisons-in-bash/#respond Mon, 13 Jan 2020 07:45:28 +0000 https://thelinuxgurus.com/?p=942 In this bash scripting tutorial, we will discuss about performing file comparisons, String comparisons as well as numeric comparisons. So let’s start with file comparisons...

The post Bash Scripting- 5 – Performing FILE, STRING comparisons & NUMERIC comparisons in Bash appeared first on The Linux GURUS.

]]>
In this bash scripting tutorial, we will discuss about performing file comparisons, String comparisons as well as numeric comparisons. So let’s start with file comparisons in bash scripts.

Recommended Read: Bash Scripting-6- Using Logical operators in shell scripts

Also Read: Important PostgreSQL commands that every beginner should know

File comparisons

The following are the parameters that can be used for file comparisons,

File Comparisons

-e file

check if file exists

-d file

check if it is a directory

-f file

check if it is a file

-r file

check if the file is readable

-s file

check if the file is not empty

-w file

check if the file is writable

-x file

check if the file is executable

-O file

check if the file is owned by the current user

-G file

check if the default group is the same as the current user

file1 -nt file2

check if file1 is newer than file2

file1 -ot file 2

check if file1 is older than file2

These comparisons parameters are one of the most frequently used parameters & you will end up using most of them on a regular basis. Now let’s example with these file comparisons in actions,

NOTE:- We write the comparative statements in brackets i.e. ‘[ ]’, whether its file, string or numeric comparisons.

#!/bin/bash

dir=/home/e2-user

if [ -d $dir ]

then

             echo “$dir is a directory ”

             cd $dir

             ls –a

else

             echo “$dir is not a directory”

fi

The above script is checking whether a directory exists & if does, it will print a message & will then also output the directory contents & if the directory does not exist then it will print a message saying that the directory does not exist.

Numeric comparisons

Now let’s see the numeric comparison in action but first let’s check the parameter that we can use for numeric comparisons,

Numeric Comparisons

n1 -eq n2

Checks if n1 is equal to n2

n1 -gt n2

checks if n1 is greater than n2

n1 -ge n2

checks if n1 is greater than or equal to n2

n1 -le n2

checks if n1 is less than or equal to n2

n1 -lt n2

Checks if n1 is less than n2

n1 -ne n2

checks if n1 is not equal to n2

Now let’s see an example to demonstrate it,

#!/bin/bash

num1=15

num2=30

if [ $num2 –gt $num1 ]

then

             echo “$num2 is greater than $num1”

fi

If [ $num1 –gt 30]

then

             echo “$num1 is greater than 30”

else

             echo “$num1 is less than 30”

fi

String Comparisons

Now is the time to discuss string comparisons, so let’s start with list of the parameters that are used for performing string comparisons,

String Comparisons

str1 = str2

check if string 1 is equal to string 2

str1 != str2

check if string 1 is not equal to string 2

str1 \< str2

check if string 1 is less than string 2

str1 \> str2

check if string 1 is greater than string 2

-n str1

check if the string 1 has a length greater than zero

-z str1

check if the string 1 has a length equal to zero

You might have noticed that we have used ‘\<’ & ‘\>’ instead of using ‘<’ & ‘>’, that is because both these symbols are used for redirection in Linux as well. So we have to use the escape symbol i.e. \. to use them for string comparisons.

Now let’s have look at some examples to demonstrate the string comparisons,

#!/bin/bash

name=”ec2-user”

if [ $USER = $name ]

then

             echo “User exists”

else

             echo “User not found”

fi

This is a simple script to check string comparisons, here we are checking a string i.e. a user name & checking it with provided name in the variable. Let’s see another example,

#! /bin/bash

str1=b

str2=y

str3=Y

if [ $str1 \> $str2 ]

then

             echo “$str1 is greater”

else

             echo “$str2 is greater”

fi

If [ $str3 \> $str1]

then

             echo “$str3 is greater”

else

             echo “$str1 is greater”

fi

Here we are comparing 3 strings with each other, we also compared a small letter with capital one. Keep in mind capital letters will be less than small letters & ‘z’ will be highest with ‘a’ as lowest letter.

We now end this tutorial on file, numeric & string comparisons. Please do send us any suggestions, queries or questions using the comment box below.

If you think we have helped you or just want to support us, please consider these:-

Connect to us: Facebook | Twitter | Linkedin

TheLinuxGURUS are thankful for your continued support.

The post Bash Scripting- 5 – Performing FILE, STRING comparisons & NUMERIC comparisons in Bash appeared first on The Linux GURUS.

]]>
https://thelinuxgurus.com/bash-scripting-5-performing-file-string-comparisons-numeric-comparisons-in-bash/feed/ 0 942
Bash Scripting-6- Using Logical operators in shell scripts https://thelinuxgurus.com/bash-scripting-6-using-logical-operators-in-shell-scripts/ https://thelinuxgurus.com/bash-scripting-6-using-logical-operators-in-shell-scripts/#respond Mon, 13 Jan 2020 07:30:55 +0000 https://thelinuxgurus.com/?p=937 We have already discussed about the conditional statements i.e. if-else, if-then-else & elif statements & have also discussed some basic shell scripts examples for those...

The post Bash Scripting-6- Using Logical operators in shell scripts appeared first on The Linux GURUS.

]]>
We have already discussed about the conditional statements i.e. if-else, if-then-else & elif statements & have also discussed some basic shell scripts examples for those as well. In this tutorial, we will discuss some advanced uses of conditional statements by using logical operators in shell scripts.

Recommended Read: Bash Scripting-7- Using FOR loop in shell script

Also Read: Recommended guide to install POSTGRESQL from Source

Logical operators or boolean operators are used for performing logical operations. Following 3 are types of logical operators,

1- Logical AND (&&):- will compare two inputs & if both are true, it will return true or else false.

2- Logical OR (||):- Will check two conditions will return true, if any of them is true & return false when both are false.

3- Not equal to (!):- will return true when the condition is false & return false if the condition is true.

Using logical operators in shell scripts

Let’s see an example to get a better understanding of & using logical operators in shell scripts,

#!/bin/bash

dir=/home/ec2-user

if [ -d $dir ] && [ -w $dir ]

then

          echo “$dir directory exists & its writable”

fi

So in this script, we are checking if a directory exists & if it’s readable. So when both of these conditions are satisfied, it will print the message that the directory exists & is readable. Here we can also repace AND logical operator with OR logical operator, the script will check if either directory is readable or is writable or both and will then print the message but will print nothing, if both conditions are false.

Relational Operators

Relational operators are used to check relation between two operands & depending upon the conditions, it will return a negative or positive outcome. Following is the list of relational operators,

Relational Operators

<=

less than or equal to

>=

greater than or equal to

<

less than

>

greater than

==

Equal to

!=

not equal to

These relational operators are used inside double parenthesis i.e. (( )).

Double Parenthesis (( ))

These are used to performing/handling advanced arithmetic operations & following paramters can be used with this,

val ++

post-increment

val —

post decrement

         ++val

pre-increment

         –val

pre decrement

!

logical NOT

&&

Logical AND

||

Logical OR

**

exponential

~

bitwise NOT operator

&

bitwise AND operator

|

bitwise OR operator

<<

left bitwise shift

>>

right bitwise shift

Now let’s discuss an example of these concepts.

#!/bin/bash

num1=15

if (( $num1 ** 2 > 100 ))

then

          (( num2=$number ** 2 ))

          echo “Square of $num1 is $num2”

fi

This simple script checks if the square of a number is greater than 100 if it is then it will calculate the square of the number & will print with a message.

Double Brackets [[ ]]

Double parenthesis “[[ ]]” is an advanced version “[ ]” & provides us with advanced features for string comparisons.

#!/bin/bash

If [[ $USER == ec2* ]]

then

          echo “Welcome $USER”

else

          echo “Who are you $USER”

fi

With this script, we are checking if there is any user that starts with ‘ec2’ & if there is any user starting with ec2, it will print a welcome message or else will ask for who the user is.

With this, we end our tutorial on using logical operators in shell scripts & also performing advanced operations for arithmetic & string comparisons. Please feel free to send in any questions, queries & suggestions using the comment box below.

If you think we have helped you or just want to support us, please consider these:-

Connect to us: Facebook | Twitter | Linkedin

TheLinuxGURUS are thankful for your continued support.

The post Bash Scripting-6- Using Logical operators in shell scripts appeared first on The Linux GURUS.

]]>
https://thelinuxgurus.com/bash-scripting-6-using-logical-operators-in-shell-scripts/feed/ 0 937
Bash Scripting-7- Using FOR loop in shell script https://thelinuxgurus.com/bash-scripting-7-using-for-loop-in-shell-script/ https://thelinuxgurus.com/bash-scripting-7-using-for-loop-in-shell-script/#respond Mon, 13 Jan 2020 07:08:59 +0000 https://thelinuxgurus.com/?p=934 Use of FOR loop in shell script is done when we need to run a command or a set of instructions/commands over & over until...

The post Bash Scripting-7- Using FOR loop in shell script appeared first on The Linux GURUS.

]]>
Use of FOR loop in shell script is done when we need to run a command or a set of instructions/commands over & over until a condition has been met. For example, changing the name of some files or changing some information about users on the system etc. Personally, I have used this many times but most recently created a script to automate AMI backup for an AWS account (there are other ways as well but i prefer my bash).

Recommended Read: Bash Scripting-8- Taking user input with READ command in shell script

Also Read: Scheduling CRON Jobs with Crontab for Beginners

Syntax for using FOR loop in shell script

for var ( var_name) in list (parameters)

do

            command

done

It seems straight forward and simple, now let’s discuss some examples for using for loop in shell script.

Example 1:-

#!/bin/bash

for name in Dan Susan Daniel

do

            echo “Welcome $name”

done

So the name of the variable is ‘name’ & list of parameters is ‘dan susan daniel’. So the output of the following script would be,

Welcome Dan

Welcome Susan

Welcome Daniel

We can also modify the script to read from a variable or use the output of a command as a list. Let’s see an example,

#!/bin/bash

name=”Dan Susan Daniel”

name=$name“monti”

for member in $name

do

            echo “Welcome again $member”

done

Now the output would be,

Welcome Dan

Welcome Susan

Welcome Daniel

Welcome monti

We can also create a file with a list & instead of writing a list inside a script, we can just mention the path of the file that has the list. Let’s see an example,

#!/bin/bash

file=”/home/ec2-user/list.txt”

for member in $(cat $file)

do

            echo “Welcome $member ”

done

/home/ec2-user/list.txt is the list & we enter names or other information either one per line, or using a single space or a tab between info. But we can’t use commas to separate them, caused by default space, tab & newlines are interpreted as separators.

Another thing that I would like to discuss is the use of escape character while using for loop in shell script. While using words like can’t, don’t, won’t, we either need to use double quotations “” or escape symbol \ in, like

“Won’t” don\’t “can’t”

Using C language style for loop in shell script

Above mentioned way is not the only method that we use for loop in shell script. We can also use the for loop C language style. Let’s see the syntax,

for ((i=0; i=10; i++))

So here, we mentioned to start loop at 0 & it can go upto 10 with an increment of one. So let’s say we need to check about system ram continuously for 10 minutes, every sixty second, then we can use this C style for loop to achieve this,

Example:

#!/bin/bash

for ((i=0; i=600; i=i+10))

do

            echo “RAM stats are”

            free -m

done

Now let’s check another example where we are also utilizing other conditional statements,

#!/bin/bash

for file in /home/ec2-user/*

do

            if [ -d “$file”]

            then

            echo”$file is a directory”

            elif [ -f “$file”]

                       echo “$file is a file not a directory”

            fi

done

So this is it for using for loop in shell script. Please feel free to send in any request, suggestion, or questions using the comment box below.

If you think we have helped you or just want to support us, please consider these:-

Connect to us: Facebook | Twitter | Linkedin

TheLinuxGURUS are thankful for your continued support.

The post Bash Scripting-7- Using FOR loop in shell script appeared first on The Linux GURUS.

]]>
https://thelinuxgurus.com/bash-scripting-7-using-for-loop-in-shell-script/feed/ 0 934
Bash Scripting-8- Taking user input with READ command in shell script https://thelinuxgurus.com/bash-scripting-8-taking-user-input-with-read-command-in-shell-script/ https://thelinuxgurus.com/bash-scripting-8-taking-user-input-with-read-command-in-shell-script/#respond Mon, 13 Jan 2020 06:57:49 +0000 https://thelinuxgurus.com/?p=930 Up until now, we have only read about using variables that we have mentioned inside the script but that’s not a good way. We might...

The post Bash Scripting-8- Taking user input with READ command in shell script appeared first on The Linux GURUS.

]]>
Up until now, we have only read about using variables that we have mentioned inside the script but that’s not a good way. We might be required to use a different value for a variable & we then need to update script each and every time. But there is a simple solution to this, taking user input with read command in the shell script.

Recommended Read: Install EPEL repository on CentOS/RHEL 6, 7 & 8

Also Read: Bash Scripting-9- using UNTIL & WHILE loop in shell script

Using read command in a shell script allows us to assign a user-entered value to a variable. Let’s show an example of how we can use read command in shell script,

#!/bin/bash

echo “ what is your name ?”

read var

echo “You are most welcome” $var

So, here we have not mentioned a variable beforehand and provided the name of the variable, just after read command. So now when the script is executed, it will ask for the name & then will assign the value to the variable named var. In the next step, it will print the welcome message along with the user-provided name.

Now let’s discuss a rather complex script than the one mentioned above,

#!/bin/bash

echo “ Please enter the full path of file/directory (ex- /home/ec2-user/new.txt)”

read path

for file in $path

do

               if [ -d “$file” ]

               then

                              echo “$file is a directory”

               elif [ -f “$file” ]

               then

                              echo “$file is a file”

               else

               echo “No file found”

done

So this script will take a directory or file path as input & based on the path provided, it will let us know whether the entered path is a file, directory or none of those.

We can also ask for some sensitive information using read command, for that we need to enter option ‘-s’, this option will hide the entered information,

# read -s variable_name

Now along with the read command, there is another way we can ask for user input from a bash script, using the following parameters,

$0, when used in script prints name of the script,

$1 will be the first value provided when running the script,

$2 will the second value provided when running the script,

$# will print the total number of values provided.

Let’s see an example of this as well,

#!/bin/bash

echo “Name of the script is $0”

echo “first value is $1”

echo “second value is $2”

echo “total numberof values are $#”

sum=$[$1 + $2]

echo “sum of $1 & $2 is $sum”

Now when we will execute the script, we must do like this,

# sh script.sh 5 15

Notice that we have mentioned 5 & 15 when executing the script. So, here $0 is the name of script i.e. ‘script.sh’, $1 is first number i.e. 5, $2 is the second 15. Similarly, we can add as variables in our script & call them when running the script.

We now end this tutorial on using read command in shell script. Please feel free to send in any questions, queries or suggestions using the comment box below.

If you think we have helped you or just want to support us, please consider these:-

Connect to us: Facebook | Twitter | Linkedin

TheLinuxGURUS are thankful for your continued support.

The post Bash Scripting-8- Taking user input with READ command in shell script appeared first on The Linux GURUS.

]]>
https://thelinuxgurus.com/bash-scripting-8-taking-user-input-with-read-command-in-shell-script/feed/ 0 930
Bash Scripting-9- using UNTIL & WHILE loop in shell script https://thelinuxgurus.com/bash-scripting-9-using-until-while-loop-in-shell-script/ https://thelinuxgurus.com/bash-scripting-9-using-until-while-loop-in-shell-script/#respond Mon, 13 Jan 2020 06:45:05 +0000 https://thelinuxgurus.com/?p=925 Loops are a very useful programming/scripting structure that runs the commands or sets of instructions until a condition has been met. In this tutorial, we...

The post Bash Scripting-9- using UNTIL & WHILE loop in shell script appeared first on The Linux GURUS.

]]>
Loops are a very useful programming/scripting structure that runs the commands or sets of instructions until a condition has been met. In this tutorial, we will learn about using until & while loops in shell script.

Let’s start out with discussing while loop in shell script

Recommended Read: Examples on how to use YUM command in Linux

Also Read: Bash Scripting-11-Input Output redirection in Linux

While loop in shell script

While loop allows us to a condition & then the loop will continue to run until the conditions are true i.e. loop will run until loop returns with a non-zero exit status. Now let’s discuss an example for using while loop in shell script,

#!/bin/bash

num=0

while [ $num -lt 10 ]

do

            echo $num

            num=$[$num+1]

done

Here, we have mentioned condition i.e. until the number is less than 10, the loop will increase the number by one & when the number reaches 10, loop will complete.

An important thing to consider is infinite loops, since the loop will continue to run until a condition is met, so if we mess up the conditions we might end up with infinite loops. Here is an example for that as well,

#!/bin/bash

num=11

while [ $num -gt 10 ]

do

            echo $num

            num=$[$num+1]

done

This loop will run until interrupted manually.

Until loop in shell script

Until loop is quite opposite of the while loop, it will run until it has exit status of zero. Here is an exmple of how we can use until loops,

#!/bin/bash

num=10

until [ $num –eq o ]

do

            echo $num

            num=$[$num-1]

done

Nested loops

We can also use one loop inside another & also one loop inside another loop. Let’s discuss an example for that as well,

#!/bin/bash

# checking nested loop

num1=10

while [ num1 –lt 20 ]

do

            echo “outer loop = $num1”

            for (( num2 = 1; $num2 > 5; num2++ ))

            do

                        num3= $[ $num1*$num2]

                        echo “Inner loop : $num1 * $num2 = $num3”

            done

num1=$[$num1+1]

done

The first loop will be called outer loop & the second loop will be called inner loop. With this we end our tutorial on using until & while loop in shell script. Please do send us any questions, queries using the comment box below.

If you think we have helped you or just want to support us, please consider these:-

Connect to us: Facebook | Twitter | Linkedin

TheLinuxGURUS are thankful for your continued support.

The post Bash Scripting-9- using UNTIL & WHILE loop in shell script appeared first on The Linux GURUS.

]]>
https://thelinuxgurus.com/bash-scripting-9-using-until-while-loop-in-shell-script/feed/ 0 925