Вы находитесь на странице: 1из 5

Linux : Bash Shell Scripting (Part 1)

Shell Script
o Shell script = program written in shells own programming language
o Text file containing collection of executable commands
o Can be created in any text editor
o No particular extension is needed, however may use .scr or .sh for your own convenience

Script has 3 parts:

(1) Declaring the shell


o Declaration of shell MUST be the very first line in the script. If omitted, it uses default shell
o Good to declare shell, since it will force that specific shell to open before the script runs (even if the
default shell that the user was using was different)
o #!/bin/bash (for bash shell) or #!/bin/ksh (for korn shell)

(2) Comment line


o Starts with #, and can occur anywhere in the script
o Eg. #This is a comment line (exception = first line that declares shell)
o Used for documentation to explain what the code is doing. Ignored by the interpreter

(3) Commands
o Can consist of any Unix/Linux command that would run at command line
o Will be executed in order from top to bottom, when we execute the script
o Blank lines can be used anywhere without impact
o Commands can be combined using pipes etc.

Making Scripts executable

o Script file should have x permission to be executable


o chmod 755 script.scr ( gives rwx r-x r-x permissions)
o chmod 700 script.scr (gives rwx --- --- permissions)
o chmod +x script.scr (gives execute permission to all)
o To run the script called script.scr, you simply type script.scr at command line (or ./script.scr)

myscript.scr (Simple script to list files one page at a time)

(1) Type in the following script into a file called myscript.scr, using any text editor

#!/bin/bash
# Script file: myscript.scr. A very simple script
ls l | more

(2) Make this file (myscript.scr) executable


(3) Type ./myscript.scr at command line to run it

praveen.mitera@senecacollege.ca
Arguments and positional parameters
o Allow us to use a general script that is more useful
o Arguments = user-supplied data that follows the script name (=input to script)
o Positional parameters = pre-defined memory variables in the shell script
o 9 positional parameters ($1, $2$9) are used to store arguments entered by user

Command line arguments (positional parameters) when running the script:


$0 name of the script
$1 first argument
$2 second argument
$3 third argument
..
$9 ninth argument
$# no. of arguments entered
$$ gives the process id PID of your process

check.scr (create script that accepts parameters)

#!/bin/bash
# script to show how parameters are accepted
clear
echo script is : $0
echo No. of arguments : $#
echo first argument : $1
echo second argument : $2
echo process id : $$

script2.scr (display specific lines from a file)

Display the first 3 lines of file1 : head -3 file1


Display the last 3 lines of file1 : tail -3 file1
Make the script executable. Run and see results ( to run: ./script2.scr)

script3.scr (accept parameters to display lines from a file)

Do the same as above, but pass the # of lines and filename as parameters to the script
head -$1 $2
tail -$1 $2

./script3.scr 3 file1 (will display 3 ilnes from top and 3 lines from bottom of file1)

script4.scr (combine commands with pipe symbol inside a script)

Create script containing combination of 2 commands with pipe symbol


head 7 file1 | tail 2 (will show lines 6 and 7 from file1)

Rewrite the above to be flexible with positional parameters:


head -$1 $2 | tail -$3
(will expected 3 parameters to be passed: # of top lines, filename, # of bottom lines)

praveen.mitera@senecacollege.ca
Mathematical operators (Eg. - + * / )

To evaluate mathematical expressions, use double round brackets around the expression
((num=15*6))
echo $num

Return value: (zero or non-zero)

In Bash shell, the return value of a program or command can be checked with $?
Assume that file file1 exists and file3 does not.

ls file1
echo $? (will return 0 : success)

ls file3
echo $? (will return 1 or another non-zero value: failure)

Relational operators Eg. > < == >= <= !==

These determine relationship between 2 values and return true/false


a=5 assigns value of 5 to variable a
((a==5)) checks if a is equal to 5 and returns zero if true
((a!=5)) checks if a is NOT equal to 5 and returns a non-zero value like 1, if false

Logical operators Eg. not (!) and (&&) or (||)

Combine logical values and return true/false


(( 7>5 && 6>5 ))
echo $?
Shows 0 (true)

File status operators

Report the status of a file (use double square brackets):


[[ -a file1 ]] (true if file1 exists)
[[ -r file1 ]] (true if file1 exists and has read access)
[[ -x file1 ]] (true if file1 exists and has execute access)
[[ -d file1 ]] (true if file1 exists and is a directory)
[[ -s file1 ]] (true if file1 exists and its size is greater than 0)
[[ file1 nt file2 ]] (true if file1 is newer than file2)
[[ file1 -ot file2 ]] (true if file1 is older than file2)

Script (backup)

cp -i $1 ~/Backup copies filename passed to script into ~/Backup directory under the same name
cp -i $1 ~/Backup/$1.bak copies filename passed to script into ~/Backup directory under same name followed by .bak
cp -i $1 $2 ~/Backup copies 2 filenames passed to script into ~/Backup directory under the same names
cp -i $@ ~/Backup copies all filenames passed to script into ~/Backup directory under the same names

praveen.mitera@senecacollege.ca
the FOR loop

Used for repetitive execution of a block of commands in a shell script


for variable [in argument-list]
do
commands
done

for loop : feeding values into the loop:


for people in Debbie Jamie John
do
echo $people
done

Accept numbers 1 to 6 as argument list and display them using a for loop
for i in 1 2 3 4 5 6
do
echo $i
done

To run the same loop as above, but make it flexible by accepting 6 parameters from user:
for i in $1 $2 $3 $4 $5 $6
do
echo $i
done

For above loop, to accept ALL parameters that user enters (HINT: use $* or $@ to capture all parameters):
for i in $*
do
echo $i
done

The above loop can also be written as follows :


for i # this is same as saying for i in $@ or for i in $*
do
echo $i
done

if statement
if (( $# == 0 )) # checks if user entered atleast one parameter
then
echo " please enter atleast one parameter"
exit 1 # exit statement makes the script STOP
fi

if-then-else statement
egrep apples file1
if (( $? == 0 )) #checks if previous command was successfull
then
echo previous command was successfull"
else
echo previous command was NOT successfull"
fi
praveen.mitera@senecacollege.ca
The WHILE loop

while condition
do
Commands
done

#!/bin/bash
# to demonstrate the while loop
secretnumber=7
echo
echo "Guess the number (between 1 and 10)"
counter=1
read yourguess
while (( $yourguess != $secretnumber ))
do
echo "No. Try again."
(( counter = counter + 1 ))
echo "Guess the number (between 1 and 10)"
read yourguess
done
echo "Good. You took $counter guesses to guess the right number"

Using while loop to read the contents of a filename provided by a user:


while read var1
do
echo Here is a line: $var1
done < $1

The UNTIL loop

until condition
do
Commands
done

#!/bin/bash
secretnumber=7
echo
echo "Guess the number (between 1 and 10)"
counter=1
read yourguess
until (( $yourguess == $secretnumber ))
do
echo "No. Try again."
(( counter = counter + 1 ))
echo "Guess the number (between 1 and 10)"
read yourguess
done
echo "Good. You took $counter guesses to guess the right number"

praveen.mitera@senecacollege.ca

Вам также может понравиться