Shell Control Statements and More

Slides:



Advertisements
Similar presentations
More Shell Programming Software Tools. Slide 2 Keyword Shell Variables l The shell sets keyword shell variables. You can use (and change) them. HOME The.
Advertisements

CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Shell Programming Software Tools. Slide 2 Shells l A shell can be used in one of two ways: n A command interpreter, used interactively n A programming.
CS 497C – Introduction to UNIX Lecture 33: - Shell Programming Chin-Chih Chang
CS465 – Unix The Korn Shell (ksh).
Chapter 5 Accessing Files and Directories. How Directories Get Created OS installation: usr, dev, etc, export, kernel and others places to store installation.
More Shell Programming Learning Objectives: 1. To learn the usage of environment (shell) variables in shell programming 2. To understand the handling of.
Shell Programming Learning Objectives: 1. To understand the some basic utilities of UNIX File 2. To compare UNIX shell and popular shell 3. To learn the.
Shell Programming 1. Understanding Unix shell programming language: A. It has features of high-level languages. B. Convenient to do the programming. C.
Bash Shell Scripting 10 Second Guide Common environment variables PATH - Sets the search path for any executable command. Similar to the PATH variable.
Introduction to Linux and Shell Scripting Jacob Chan.
Shell Programming. Shell Scripts (1) u Basically, a shell script is a text file with Unix commands in it. u Shell scripts usually begin with a #! and.
Shell Script Examples.
Shell Control Structures CSE 2031 Fall August 2015.
CTEC 1863 – Operating Systems Shell Scripting. CTEC F2 Overview How shell works Command line parameters –Shift command Variables –Including.
Shell Programming, or Scripting Shirley Moore CPS 5401 Fall August 29,
Agenda Control Flow Statements Purpose test statement if / elif / else Statements for loops while vs. until statements case statement break vs. continue.
1 Operating Systems Lecture 3 Shell Scripts. 2 Shell Programming 1.Shell scripts must be marked as executable: chmod a+x myScript 2. Use # to start a.
1 Operating Systems Lecture 3 Shell Scripts. 2 Brief review of unix1.txt n Glob Construct (metacharacters) and other special characters F ?, *, [] F Ex.
8 Shell Programming Mauro Jaskelioff. Introduction Environment variables –How to use and assign them –Your PATH variable Introduction to shell programming.
Chapter 5 Bourne Shells Scripts By C. Shing ITEC Dept Radford University.
1 Shell Programming – Extra Slides. 2 Counting the number of lines in a file #!/bin/sh #countLines1 filename=$1#Should check if arguments are given count=0.
The UNIX Shell. The Shell Program that constantly runs at terminal after a user has logged in. Prompts the user and waits for user input. Interprets command.
Introduction to Linux OS (IV) AUBG ICoSCIS Team Prof. Volin Karagiozov March, 09 – 10, 2013 SWU, Blagoevgrad.
1 Shell Scripting (C shell) SungHo Maeung 10/27/2000 Tutorial section Computer Science Lab.
Writing Shell Scripts ─ part 3 CSE 2031 Fall October 2015.
Linux Operations and Administration
Keyword Shell Variables The shell sets keyword shell variables. You can use (and change) them. HOME The path to your home directory PATH Directories where.
UNIX Shell Script (1) Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology
Course materials may not be reproduced in whole or in part without the prior written permission of IBM. 5.1 © Copyright IBM Corporation 2008 Unit 11: Shell.
CS465 - UNIX The Bourne Shell.
UNIX Commands. Why UNIX Commands Are Noninteractive Command may take input from the output of another command (filters). May be scheduled to run at specific.
CSC 352– Unix Programming, Spring 2015 March 2015 Shell Programming (Highlights only)
Shell Programming. Creating Shell Scripts: Some Basic Principles A script name is arbitrary. Choose names that make it easy to quickly identify file function.
1 Operating Systems Lecture 2 UNIX and Shell Scripts.
Unix/Linux cs3353. The Shell The shell is a program that acts as the interface between the user and the kernel. –The shell is fully programmable and will.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
Writing Scripts Hadi Otrok COEN 346.
Shell Programming Learning Objectives: 1. To understand the some basic utilities of UNIX File 2. To compare UNIX shell and popular shell 3. To learn the.
1 © 2000 John Urrutia. All rights reserved. Session 5 The Bourne Shell.
CSCI 330 UNIX and Network Programming Unit IX: Shell Scripts.
Compunet Corporation Introduction to Unix (CA263) Your Environment By Tariq Ibn Aziz Dammam Community College.
Environment After log in into the system, a copy of the shell is given to the user Shell maintains an environment which is distinct from one user to another.
1 Unix/Linux commands and shell programming-Part 2 (Dr. Mohamed El Bachir Menai)
More Shell Programming. Slide 2 Control Flow  The shell allows several control flow statements:  if  while  for.
Group, group, group One after the other: cmd1 ; cmd2 One or both: cmd1 && cmd2 Only one of them: cmd1 || cmd2 Cuddling (there):( cmd1 ; cmd2 ) Cuddling.
CSCI 330 UNIX and Network Programming Unit X: Shell Scripts II.
Assigning Values 1. $ set One Two Three [Enter] $echo $1 $2 $3 [Enter] 2. $set `date` [Enter] $echo $1 $2 $3 [Enter] 3. $echo $1 $2 $3 $4 $5 $6 [Enter]
By Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
1 UNIX Operating Systems II Part 2: Shell Scripting Instructor: Stan Isaacs.
 Prepared by: Eng. Maryam Adel Abdel-Hady
Shell Control Structures CSE 2031 Fall June 2016.
INTRODUCTION TO SHELL SCRIPTING By Byamukama Frank
ULI101 Week 10. Lesson Overview ● Shell Start-up and Configuration Files ● Shell History ● Alias Statement ● Shell Variables ● Introduction to Shell Scripting.
Bash Shell Scripting 10 Second Guide.
Shell Control Structures
Agenda Bash Shell Scripting – Part II Logic statements Loop statements
CSC 352– Unix Programming, Fall 2012
Shell Script Assignment 1.
Writing Shell Scripts ─ part 3
Writing Shell Scripts ─ part 3
Agenda Control Flow Statements Purpose test statement
Linux Shell Script Programming
CSC 352– Unix Programming, Fall, 2011
Chapter 5 Bourne Shells Scripts
More Shell Programming
Chapter 3 The UNIX Shells
Introduction to Bash Programming, part 3
Review.
Review The Unix Shells Graham Glass and King Ables,
Presentation transcript:

Shell Control Statements and More CS465 - UNIX Shell Control Statements and More

while statement while [ condition ] do command(s) done Same condition syntax as if statement Begin and end of command block defined by keywords do...done Loops while condition is TRUE while [ condition ] do command(s) done

while Loop Example #1 $ cat wake #!/bin/sh resp="n" while [ "$resp" != "y" ] do echo "Wakeup [y/n]? " read resp done $ $ wake Wakeup [y/n]? n Y Wakeup [yes/no]? y $

while Loop Example #2 #!/bin/sh echo "Enter number: " read num fac=1 $ cat fac #!/bin/sh echo "Enter number: " read num fac=1 loop=1 while [ $loop -le $num ] do fac=`expr $fac \* $loop` loop=`expr $loop + 1` done echo "The factorial of $num is $fac" $ $ fac Enter number: 5 The factorial of 5 is 120 $

while example #3 $ cat lines while [ "$input" != done ] do echo 'Enter a filename, or "done":' read input if [ "$input" != done ] then lines=`wc –l < $input` echo "$input has $lines lines" fi done $ $ lines Enter a filename, or "done": shoes shoes has 12 lines done $

while example #4 $ cat sayhi #! /bin/sh # $* = list of names count=$# while [ count -gt 0 ] do echo Hello $1 count=`expr $count - 1` shift done exit 0 $ sayhi Sue Joe Bob Hello Sue Hello Joe Hello Bob $

Student Exercise Write a shell script called up, that will move you up in the directory structure If no arguments, move up ONE directory If one argument, it should be a number, telling how many directories to move up Usage Example: $ pwd /usr/home/faculty/small000 $ . up 2 /usr/home $ . up /usr

Exercise Sample Solution #! /bin/sh # $1 = number of levels to go up # (if no parameters, go up one level) # if [ $# -eq 0 ] then count=1 else count=$1 fi while [ $count -gt 0 ] do cd .. count=`expr $count - 1` done exit 0

for Statement The for statement is used to repeat commands for known or “fixed” values Unlike C programming, the for loop usually repeats tasks for “arguments” that are either issued from the script or a stated directory after for statement.

for statement for variable in list do command(s) done variable is a variable name; don't use $ list is a space-separated list of strings. Each element of the list will be assigned to variable one at a time, and the command block will be executed. Within the command block, use $variable to use the value that has been assigned. for variable in list do command(s) done

for example #1 $ cat colorscript #!/bin/sh for color in red yellow blue do echo $color done echo "the end" $ colorscript red yellow blue the end $

for example #2 $ cat userdirs #!/bin/sh for user in $* do echo Directory for: $user ls -F /home/${user} done $ Note: If the “in ___” part is omitted, for defaults to “in $* $ userdirs jmsmith krjones Directory listing for: jmsmith cprogs/ dotask* xfile diskfile mbox Directory listing for: krjones mbox prog1.c prog2.c $

for example #3 $ cat printall #!/bin/sh for file in * do if [ -f $file ] then echo "Print $file [y/n]? " read resp if [ $resp = "y" ] lpr $file fi done $ $ printall letter1 names Print letter1 [y/n]? y Print names [y/n]? n

case statement Very similar to C switch statement: executes the commands after a choice that matches string. Double-semicolon ends a block of commands, like the C break statement. If you skip the ;; you will keep going into the next block . * as a choice will match any string, and can be used to set a default esac ends the statement. case string in choice) command(s) ;; choice) command(s) esac

case Example #1 echo Enter command and filename read cmd file case "$cmd" in list) ls -l "$file" ;; count) wc -l "$file" *) echo "command $cmd is not implemented" esac

case Example #2 $ cat yesno #! /bin/sh echo –n 'Yes or No (y/n)? ' read choice case $choice in "Y" | "y") echo You chose Yes;; "N" | "n") echo You chose No;; *) echo Invalid choice;; esac exit $ yesno Yes or No (Y/N)? N You chose No $

case Example #3 The following will be a script to: Give user a choice of what to do with the files listed as arguments: Copy to a subdirectory Concatonate or Delete Carry out the action chosen, prompting for the subdirectory or file to concatonate into, as needed. Display a message confirming action was done.

case Example #3 (Continued on next slide) $ cat files #! /bin.ksh # script parameters = files to operate on cat << STOP M) Move Files C) Concatonate Files D) Delete Files Enter choice: STOP read choice (Continued on next slide)

case Example #3 (continued) case $choice in "m"|"M") echo Move files to which subdir? read subname if [ ! -d $subname ] then mkdir $subname fi mv $* $subname echo Files moved to subdir $subname ;; "c"|"C") echo File to place concatonation in? read fname if [ -f $fname ] echo Error - $fname already exists else cat $* > $fname echo Files concated into $fname

case Example #3 (continued) "d"|"D") rm $* echo Files $* have been deleted ;; *) echo Invalid Choice -- No Can Do esac exit 0 $ files file1 file2 M) Move Files C) Concatonate Files D) Delete Files Enter choice: C File to place concatonation in? combo Files concated into combo $

How the Shell Finds a Command The shell searches a list of directories for an executable file with the same name as the command given. The list of directories is stored in the PATH variable $ PATH=/bin:$PATH (sh/ksh) If there is a match in more than one directory, the shell uses the first one it finds. To run a command not in one of these directories, give a pathname (relative or absolute) instead. $ ~/progs/dosomething

Built-In Commands Some commands are built into the shell kernel. The echo command, for example, is often builtin, for efficiency. You can find out where the shell is getting a particular command using the “which” command in any shell: $ which echo echo: shell built-in command. $ which cat /usr/bin/cat $

More Environment Variables Predefined Environmental Variables: PPID shell’s parent’s process id IFS list of command line word delimiters (default is list is space, tab & newline) PS1 your shell prompt (default is $) PS2 your input prompt (default is >) SHENV directory where your .profile is located (default is $HOME)

Files Run at Login System-wide login file /etc/profile Personal login file $HOME/.profile Personal environment file Set by $ENV Usually $HOME/.kshrc

Sample Bourne .profile # Set PATH PATH=$PATH:. export PATH # Set environmental variable file ENV=$HOME/.envsetup # Set shell variables PS1='Command? ' # Display status information date echo "Currently logged in users:“ users

Directory in prompt To include directory in prompt, put these lines in your .profile file: PS1='$PWD $ ' or PS1="`pwd`$ " export PS1