21
Linux Shell script (Bash) Basics PART - 1 1

Bash Shell Scripting

Embed Size (px)

Citation preview

Page 1: Bash Shell Scripting

1

Linux Shell script (Bash) Basics

PART - 1

Page 2: Bash Shell Scripting

2

A script is a list of system commands stored in a file.

Steps to write a script :-

Use any editor like vi or vim

chmod permission your-script-name.

Examples:-

$ chmod +x <filename.sh>

$ chmod 755 <filename.sh>

Execute your script as:

$ bash filename.sh $ bash fileneme.sh $ ./filename.sh

Page 3: Bash Shell Scripting

3

My first shell script

clear echo “hello world“

$ ./first

$ chmod 755 first

$ ./first

Variables in Shell:

In Linux (Shell), there are two types of variable:

(1) System variables :

(2) User defined variables :

Page 4: Bash Shell Scripting

4

$ echo $USERNAME

$ echo $HOME

User defined variables :

variable name=value

Examples:

$x = 10

echo Command:

echo command to display text

Page 5: Bash Shell Scripting

5

arithmetic operations

Syntax:

expr op1 math-operator op2

Examples:

$ expr 10 + 30

$ expr 20 – 10

$ expr 100 / 20

$ expr 200 % 30

$ expr 100 \* 30

$ echo `expr 60 + 30`

Shell Arithmetic

Page 6: Bash Shell Scripting

6

Renaming filesmv test1 test2

Deleting filesrm -i test1

Creating directoriesmkdir dir3

Deleting directoriesrmdir dir3

Page 7: Bash Shell Scripting

7

$ ps PID TTY TIME CMD

$ ps -efUID PID PPID C STIME TTY TIME CMD

$ ps -lF S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME

CMD

$ ps -efHUID PID PPID C STIME TTY TIME CMD

processes

Page 8: Bash Shell Scripting

8

Creating files:

$ touch test1$ ls -il test1

Copying files:

cp source destinationcp test1 test2

Linking files:

There are two different types of file links in Linux:

a. A symbolic, or soft, linkb. A hard link

Page 9: Bash Shell Scripting

9

" Double Quotes

Double Quotes" - Anything enclose in double quotes removed meaning of that characters (except \ and $).

' Single quotes 'Single quotes' - Enclosed in single quotes remains unchanged.

` Back quote `Back quote` - To execute command

Quotes

Page 10: Bash Shell Scripting

10

Pipes:

who | wc –l

Reading from Files:

$ read message $ echo $message

Read command to read lines from files

Command substitution:

Var=`date` Var=$(date)

Background Processes:

ls -R /tmp &

Page 11: Bash Shell Scripting

11

while read ip name alias do if [ ! -z “$name” ]; then # Use echo -en here to suppress ending the line; # aliases may still be added echo -en “IP is $ip - its name is $name”if [ ! -z “$aliases” ]; then echo “ Aliases: $aliases” else # Just echo a blank line echo fi fi done < /etc/hosts

Reading with While

Page 12: Bash Shell Scripting

12

Stopping processeskill piddisk space$ df$ df –hDisk usages:$ du

Commands:$ cat file1$ sort file1$ cat file2$ sort file2$ sort -n file2

Page 13: Bash Shell Scripting

13

grep [options] pattern [file]

The grep command searches either the input or the file you specify for lines that contain characters that match the specified pattern. The output from grep is the lines that contain the matching pattern.

Searching for data

Page 14: Bash Shell Scripting

14

$ cat random.sh#!/bin/bashMIN=200MAX=500let “scope = $MAX - $MIN”if [ “$scope” -le “0” ]; thenecho “Error - MAX is less than MIN!”fifor i in `seq 1 10`dolet result=”$RANDOM % $scope + $MIN”echo “A random number between $MIN and $MAX is $result”Done

$ ./random.sh

RANDOM produces a random number between 0 and 32767. This simple recipe produces 10 randomnumbers between 200 and 500:

Page 15: Bash Shell Scripting

15

$ cat hypotenuse.sh#!/bin/sh# calculate the length of the hypotenuse of a Pythagorean

triangle# using hypotenuse^2 = adjacent^2 + opposite^2echo -n “Enter the Adjacent length: “read adjacentecho -n “Enter the Opposite length: “read oppositeosquared=$(($opposite ** 2)) # get o^2asquared=$(($adjacent ** 2)) # get a^2hsquared=$(($osquered + $asquared)) # h^2 = a^2 + o^2hypotenuse=`echo “scale=3;sqrt ($hsquared)” | bc`# bc does sqrtecho “The Hypotenuse is $hypotenuse”

Problem 1: Code to calculate the length of the hypotenuse of a Pythagorean triangle

Page 16: Bash Shell Scripting

16

There are two types of environment variables in the bash shell

Global variables Local variables

Environment Variables

Page 17: Bash Shell Scripting

17

An array is a variable that can hold multiple values.

To set multiple values for an environment variable, just list them in parentheses, with each value

separated by a space: $ mytest=(one two three four five) $ Not much excitement there. If you try to display the array

as a normal environment variable, you’ll be disappointed: $ echo $mytest one $ Only the first value in the array appears. To reference an

individual array element, you must use a numerical index value, which represents its place in the

array. The numeric value is enclosed in square brackets: $ echo ${mytest[2]} three $

Variable Arrays

Page 18: Bash Shell Scripting

18

$ date ; who

$ chmod u+x test1

$ ./test1

$ echo This is a test

This is a test

$ echo Let’s see if this’ll workLets see if thisll work$

Scripting basics

Page 19: Bash Shell Scripting

19

One of the most useful features of shell scripts is the lowly back quote character, usually called the

backtick (`) in the Linux world.

You must surround the entire command line command with backtick characters:

testing=`date`

$ cat test5#!/bin/bash# using the backtick charactertesting=`date`echo "The date and time are: " $testing$

The backtick

Page 20: Bash Shell Scripting

20

Output redirection

The most basic type of redirection is sending output from a command to a file. The bash shell uses the greater-than symbol for this:

command > outputfile

Input redirection

Input redirection is the opposite of output redirection

The input redirection symbol is the less-than symbol (<):

command < inputfile

Redirecting Input and Output

Page 21: Bash Shell Scripting

21

$ expr 1 + 56The bash shell includes the expr command to stay

compatible with the Bourne shell; however, italso provides a much easier way of performing mathematical

equations

$ var1=$[1 + 5]$ echo $var16$ var2 = $[$var1 * 2]$ echo $var212$

The expr command