1 / 29

03-60-256-01 System Programming Shell Programming

03-60-256-01 System Programming Shell Programming. Quazi Rahman [Modified from slides by Dr. B. Boufama ] School of Computer Science University of Windsor Winter, 2013. Outline. Shell Programs: Scripts Shell and Environment Variables Quoting BASH as a Programming Language Exercises.

claude
Download Presentation

03-60-256-01 System Programming Shell Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 03-60-256-01System ProgrammingShell Programming QuaziRahman [Modified from slides by Dr. B. Boufama] School of Computer Science University of Windsor Winter, 2013

  2. Outline • Shell Programs: Scripts • Shell and Environment Variables • Quoting • BASH as a Programming Language • Exercises

  3. Shell programs: Scripts • Shells are more than just command interpreters • They have their own programming languages. • Shell programming (shell scripts) are excellent for concise file system operations and scripting the combination of existing functionality in filters and command line tools via pipes. • A shell script, (shell program),is a file that contains various shell commands. • A shell language can also: • Define, read and write variables (shell variables) • Implement control structures such as for and while loops and, if and switch • Define and use functions Shell Scripts

  4. Shell programs: Scripts export EDITOR=emacs if [[ $REMOTEHOST ]]; then if [[ $REMOTEHOST == "csgate.uwindsor.ca“ ]]; then export DISPLAY="U96.lamf.uwindsor.ca:0.0" else export DISPLAY=$REMOTEHOST":0.0" fi else export DISPLAY=$HOST":0.0" fi Shell Scripts: Example

  5. Shell programs: Scripts • Make the file executable: • chmod +x script_file • The name script_file becomes like a command. To execute: • bravo:~/ script_file • Different shells have different syntax. • A Bash shell script won’t be run by C-shell or Korn shell. • The shell to be used for a script is chosen as follow: • If the first line of the script consists of the only character #, then the script is interpreted by the shell from which it has been called. • If the first line of the script is of the for #!fullPathName, then the program fullPathName is used. • Otherwise, the Bourne shell is used. How to Run a Script?

  6. Shell programs: Scripts • #!/bin/csh#This is a sample C-shell script echo -n the date of today is’ ’# -n omits new line date • #!/bin/ksh #This is a sample K-shell script echo “the date of today is \c” # \c omits new line Date • #!/bin/bash #This is a sample BASH script echo -n “the date of today is ”# -n omits new line date Example

  7. Shell programs: Scripts #!/bin/bash # This is a simple bash shell script to print the date. # If you put a command in back ticks, you can save it to a variable #+ to use later, or you can put it directly into another command. todays_date=`date` # Use a dollar sign ($), to access the value of variables. echo "The date of today is $todays_date" echo "The date of today is still `date`" # If you need to omit the newline on the echo, use the -n option #+ and run the date command on the following line. echo -n "And once again, the date is " date Tips on BASH Scripts

  8. Shell programs: Scripts $0- Name of the program that is running $1...$9 - Values of command line arguments 1 through 9 $* - Values of all command line arguments $# - Total number of command line arguments $$ - Process ID of current process $? - Exit status of most recent command $! - PID of most recent background process Some read-only shell/environment variables

  9. Quoting • The shell’s wildcard/variable/command substitution mechanism can be inhibited using quotes: • Single quotes (‘ ’) inhibit wildcard/variable/command substitution. • Double quotes (“ ”) inhibit wildcard replacement only. • Back quotes (` `) used for command execution • When quotes are nested, only the outer quotes matter. • Example echo 3 * 5 = 15 won’t work because * is a wildcard (although echo3*5=15 might work! Why?) echo ’3 * 5 = 15’  3 * 5 = 15 echo ’I am $USER’  I am $USER echo “I am $USER”  I am rahmanq echo “Today is `date`”  Today is Sat Jan 12 16:09:00 EST 2013 Quoting

  10. BASH as a Programming Language • Built-in programming languages • In addition to the basic facilities, shells have built-in programming languages that support for: • conditions, • loops, • input/output • basic arithmetic • It supports user defined variables and commands (like functions in C) BASH as a Programming Language

  11. BASH as a Programming Language Example 1: #!/bin/bash echo -n "Enter a value> " read a echo -n "Enter another value> " read b echo "Doing arithmetic> " # When assigning variables, no space on either side of the #+ equal sign. To do arithmetic in bash, surround the #+ expression with $(( and )). sum=$(( $a + $b )) echo "The sum a + b is $sum" BASH as a Programming Language

  12. BASH as a Programming Language Example 1 (cont’d): difference=$(( $a - $b )) echo "The difference a - b is $difference" product=$(($a * $b)) echo "The product a * b is $product" if [[ $b -ne 0 ]]; then quotient=$(($a / $b)) echo "The division a / b is $quotient" else echo "The division a/b is impossible" fi BASH as a Programming Language

  13. BASH as a Programming Language Example 1 (enhanced): #!/bin/bash if [ $#!= 2 ]; # or, if ( test $# != 2 ) then echo “Usage: $0 integer1 integer2” else echo “Doing arithmetic> “ r=$(($1 + $2)) ; echo “the sum "$1" + "$2“ is $r” r=$(($1 - $2)) ; echo "the subtraction "$1" - "$2" is $r“ r=$(($1 * $2)) ; echo "the product $1 * $2 is $r“ if [ $2 -ne 0 ] ; then r=$(($1 / $2)) ; echo "the division $1 / $2 is $r" else echo "the division $1 / $2 is impossible" fi fi BASH as a Programming Language

  14. BASH as a Programming Language • Accessing a simple variable: • $VAR # access the value of variable VAR • Example: dir=“/export/home/” echo my home is ${dir}rahmanq/ my home is /export/home/rahmanq/ • List variables: name=(arg1 arg2 ...) names=( Windsor Toronto Ottawa ) echo ${names[0]}  Windsor echo ${names[@]:1:2}  Toronto Ottawa echo ${names[*]}  Windsor Toronto Ottawa echo ${#names[@]}  3 #number of elements names=(${names[@]} London) #add a new element names[1]=Quebec #change element 1 (2nd element) echo $names[@]  Windsor Quebec Ottawa London Accessing variables

  15. BASH as a Programming Language • String expressions: • in addition to == and != we have • =~ like == but right side may contain wildcards • !~like != but right side may contain wildcards • Arithmetic expressions: • Similar to the C arithmetic operators, however, only integers are supported. String and Arithmetic expressions

  16. BASH as a Programming Language • Example: (Use of “let”) #!/bin/bash if [[ $1 > 0 && $(($2 % 10)) != 0 ]]; then echo Operands are valid let “a = $2 % 10” let “r = $(($1 * $2)) / $a” echo "expression value is $r" else echo "Operand problem" fi String and Arithmetic expressions

  17. BASH as a Programming Language #!/bin/bash if [ $# -ne 2 ] # Argument check then echo "Usage: $0 first-number second-number" exit 1 fi gcd () { dividend=$1; divisor=$2; remainder=1 until [ "$remainder" -eq 0 ] do let "remainder = $dividend % $divisor" dividend=$divisor; divisor=$remainder done } gcd $1 $2 echo; echo "GCD of $1 and $2 = $dividend"; echo Example: gcd

  18. BASH as a Programming Language • bravo:~/ test expression, or [ expression ] • The value is 1 if the selected option is true and 0 otherwise. • Available options: • For expression as: fileName1 –option fileName2 • nt – fileName1 newer than fileName2 • ot – fileName1 older than fileName2 • For expression as: –option fileName r – Shell has the permission to read from the fileName w – Shell has the permission to write into the fileName x – Shell has the permission to execute the fileName e – fileName exists o – fileName is owned by shell’s user z – file exists but is of size 0 f – fileName is a regular file not a directory d – fileName is a directory Expressions for File `test`

  19. BASH as a Programming Language #!/bin/bash echo -n "Enter file name> " read file # Use elif in bash for the “else if” construct. # The “>>” in the example is output redirection with appending. # The output of the ls command will be appended to the file. if [ -w "$file" ]; then ls >> $file echo "More input has been appended" elif [ -e "$file" ]; then echo "You have no write permission on $file" else echo "$file does not exist" fi Example

  20. BASH as a Programming Language • Bash supports several control structures, in particular: • if statement: 1. if [ expr]; then #–> “if” {code} fi 2. if [ expr] #–> “if-else” then {code} else {code} fi 3. if [ expr1 ]; then #–> “if-else-if” {code} elif [ expr2 ] then {code} else {code} fi • if [ expr] • then {code} • fi Control structures if [expr]; then {code}; fi if [expr]; then {code}; else {code}; fi Try This one your selves.

  21. BASH as a Programming Language #!/bin/bash echo -n "Enter file name> " read file if [ ! -e $file ]; then echo "Sorry, $file does not exist." elif [ ! -w $file ]; then echo "You have no write permission on $file“ if [ -o $file ]; then chmodu+w $file #(grant write permission) echo "Write permission granted" else echo "Write permission cannot be granted" echo "because you don't own this file" fi else ls >> $file echo "More input has been appended" fi Example: append to a file

  22. BASH as a Programming Language • while loops have the style of [tests statements]do and they end with done #!/bin/bash secretCode=zoom99 echo -n "Guess the code> " read yourGuess while [ $secretCode != $yourGuess ]; do echo "Good guess but wrong, try again" echo -n "Enter your guess> " read yourGuess done echo "BINGO!" exit 0 • An infinite loop with a while can be done by using a colon (:) as the test condition. while : ; do {code} done While-do

  23. BASH as a Programming Language • Case statements have the following structure. case $choice in [cC]) exec /bin/csh ;; [bB]) exec /bin/bash ;; [kK]) exec /bin/ksh ;; *) echo "Wrong choice, try again“ read choice esac Case (Switch) Statement

  24. BASH as a Programming Language • There are a few ways to write for-loop for VAR in {VAR value list} ; do { code } done for (( i=0; i<5; i++ )) do { code } done for people in $1 $2 $3 $4; do # using command line arguments echo $people done for people in $*; do # using all command line arguments echo $people done For Loop

  25. BASH as a Programming Language • Syntax: until-do • until [ i -eq 10 ]do   {code}   let i++done declare -a array #declare an array without initialization for name in $*; do array=("${array[@]}" $name) done echo ${array[@]} #print all the array elements i=0 until [ $i -eq $# ]; do echo -n ${array[$i]} #print one array element echo let i++ done Repeat Until

  26. BASH as a Programming Language • Use the trap command to handle signals in bash. • Unlike csh, you can trap any signal (except for SIGKILL of course) #!/bin/bash trap ' { echo "CTRL-C by user, Finishing, bye bye :)" exit 1 }' INT while : ;do echo "Infinite loop!!!!" sleep 5 done • To ignore any interrupt, use trap ‘ ’ INT • Notice that csh uses – with no argument to ignore a signal. • Since SIGINT won't work (CTRL-C), you can use (CTRL-Z) to pause the job. • ``ps'' to find the running processes and ``kill -9 <pid>'' to kill the process. #!/bin/bash trap '' INT while : ;do echo "Infinite loop!!!!" sleep 5 done Trap Command

  27. BASH as a Programming Language #!/bin/bash trap '' INT clear stty –echo #turn off the echo mechanism echo -n "Enter your passwd here> " read secretPass echo " " echo -n "Confirm your passwd here> " read confirmPass echo " " if [ "$secretPass" != "$confirmPass" ]; then echo "Work on your short-term memory first" exit 1 fi yourGuess="" while [ "$yourGuess" != "$secretPass" ]; do clear echo -n "Enter password to unlock screen> " read yourGuess echo " " done clear echo "You're back in the system!" • stty echo #turn on the echo mechanism exit 0 Example

  28. Summary • When you log onto a Unix machine, the operating system runs a program, called shell. • A shell provides a prompt and waits for you to type in commands. • A shell command can be a built-in (internal) or an external command. • To execute an external command, the shell searches for its binary file in several directories, the search path. • The search path is stored in a shell variable called PATH • There are several shells, the most common ones are the Bourne Again shell, the Korn shell and the C shell. • A shell has the built-in capability for numeric, string and file expressions. • A shell has most control structures found in a programming language • A shell has means to define and use simple variables and list variables(arrays). • The shell makes it easy for a programmer to write useful programs. • You can debug a Bash shell program by using: bash –xv script_file Summary

  29. Exercises • Write a bash-shell script to separately list directories and files. • Write a bash-shell script to list all regular files in the current directory that are smaller than n bytes (n is an integer argument). • Write a bash-shell script to replace all occurrences of a word by another word in a file. • Synopsis: replaceWord < inFile > < word > < repWord > < outFile > • Write a bash-shell script to calculate the Fibonacci numbers • given by: 0, if n = 0 Fn = 1, if n = 1 Fn-1 + Fn-2, if n > 1 • Synopsis: fibonacci < integer > Exercises

More Related