bash Archives - The Linux GURUS https://thelinuxgurus.com/tag/bash/ Learn Linux & DevOPS from THE LINUX GURUS Tue, 16 Jun 2020 06:49:20 +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 Archives - The Linux GURUS https://thelinuxgurus.com/tag/bash/ 32 32 148921671 Learn to use KILL COMMAND in Linux https://thelinuxgurus.com/learn-to-use-kill-command-in-linux/ https://thelinuxgurus.com/learn-to-use-kill-command-in-linux/#respond Tue, 16 Jun 2020 06:51:20 +0000 https://thelinuxgurus.com/?p=981 At one time or another, you must have faced the problems with Linux processes, either process are stuck or are unresponsive completely. Some of the...

The post Learn to use KILL COMMAND in Linux appeared first on The Linux GURUS.

]]>
At one time or another, you must have faced the problems with Linux processes, either process are stuck or are unresponsive completely. Some of the time the process restart also does not work & the only thing that can be done is terminating the process completely, that’s where the kill command comes in handy.

Recommended Read: How to change timezone in Linux

Also Read: Examples on how to use PS COMMAND in Linux

There are many other commands as well that can perform the same operation but kill command is most popular & widely used. Let’s see the syntax for using kill command,

Syntax

# kill -signal pid(process_id)

It provides a lot of options i.e. signal to handle the processes. Let’s discuss a little more about kill command with the help of some examples.


Examples

List all the kill signals available

Kill has a lot of signals available to manage the running or stuck processes & we should know how to check & use them. To get the complete list of all kill signals, the command is

# kill -l

kill command

So there are 63 signals that we can use with kill command but most of them are not used at all. The mostly used signals are,

  • 1 (HUP) – Reload a process

  • 9 (KILL) – Kill a process

  • 15 (TERM) – Gracefully stop the process


Stop a process

To stop a process, we must know the process id which can be obtained by using the ps command,

# ps -ef | grep haproxy

Or you can also use another command to get the process id,

# pidof haproxy

Once you have the process id, we can use it to terminate/reload or gracefully stop the process. You can use the kill command the following 3 ways,

# kill -9 pid

# kill -SIGKILL pid

# kill -KILL pid

You can either use the signal number, signal name or signal name without SIG.


Reload a process

With kill command, we can also reload the process, again we would first need the process id first. We can then use the following command to reload the process,

# kill -1 pid

# kill -SIGHUP pid

# kill -HUP pid

We can use either of the three commands.


Gracefully stop a process

To gracefully stop a process, we can use the either of the following commands,

# kill -15 pid

# kill -SIGTERM pid

# kill -TERM pid

We end this tutorial on how to use kill in Linux. Please do let us know if you have 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 Learn to use KILL COMMAND in Linux appeared first on The Linux GURUS.

]]>
https://thelinuxgurus.com/learn-to-use-kill-command-in-linux/feed/ 0 981
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
Examples on how to use PS COMMAND in Linux https://thelinuxgurus.com/examples-on-how-to-use-ps-command-in-linux/ https://thelinuxgurus.com/examples-on-how-to-use-ps-command-in-linux/#respond Thu, 16 Jan 2020 14:01:52 +0000 https://thelinuxgurus.com/?p=977 Linux has a number of processes running together without them being interfering with each other. So in order to administer a Linux system, we should...

The post Examples on how to use PS COMMAND in Linux appeared first on The Linux GURUS.

]]>
Linux has a number of processes running together without them being interfering with each other. So in order to administer a Linux system, we should also know how to effectively manage the Linux processes. There are many commands that help us accomplish that but none is as popular & widely used as ‘ps’.

PS command, ‘process status’, is used for checking & managing all the Linux processes. PS command in linux lists out all the processes that are currently running on the system. It will provide a list of processes along with their PIDs & some other information about processes as well.

Recommended Read: How to change timezone in Linux

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

Information about the processes is stored in virtual files in /proc, ps command process information from these files & provides us with the process information. In this tutorial, we will learn to use the ps command with the help of some examples.


PS command in Linux

List all processes

To get a list of all processes, use

# ps

The results will have process information in 4 columns i.e. PID- process id, TTY- terminal for user, TIME- time since the process is running, CMD- the command that launched the process.

# ps -A

# ps -e

These are other commands to get a list of all processes. To perform a full-listing of process, use

# ps -ef


Get information for a specific process

To get information about a single process, we can filter the process with ‘grep’ command,

# ps -ef | grep nagios


Get process information for the current user

To get the list of processes running under the currently logged in user, use

# ps -x


Get process information for another user

To get the list of processes running under another user, we can use the option ‘U’ with ps command,

# ps -U user_name

Or we can also mention the UID/user id instead of the user name,

# ps -U 566


Get process information for a group

To the processes running under a group, we can use option ‘G’ followed by either group name or group id,

# ps -G influxdb

# ps -G 493


Get parent & child processes

To get list of all parent & child processes, use the following command,

$ ps -C haproxy


Display processes running on a terminal

To get the list of all processes that are running on a particular terminal, we can use the following command,

# ps -t tty2


Custom output for process command

If we only need some of the fields from the output of ps command, then we can use option ‘o’ to do so,

# ps -Ao pid,cmd,user,etime

Now we will only get pid, cmd, user & etime in the output of ps command.

These were some of the examples for using ps command in Linux. There are plenty of other options that can be used with ps command also, to get the complete list of options available, we can use help,

# ps –help

We now end this tutorial on how to use ps command in Linux. Please do let us know if you have 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 Examples on how to use PS COMMAND in Linux appeared first on The Linux GURUS.

]]>
https://thelinuxgurus.com/examples-on-how-to-use-ps-command-in-linux/feed/ 0 977
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