CS465 – Unix The Korn Shell (ksh).

Slides:



Advertisements
Similar presentations
Shell Script Assignment 1.
Advertisements

CIS 240 Introduction to UNIX Instructor: Sue Sampson.
NETW-240 Shells Last Update Copyright Kenneth M. Chipps Ph.D. 1.
Chapter Seven Unix Shell Environments1 System Programming UNIX Shell Environments.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
CS 497C – Introduction to UNIX Lecture 33: - Shell Programming Chin-Chih Chang
Linux+ Guide to Linux Certification, Second Edition
Shell Basics CS465 - Unix. Shell Basics Shells provide: –Command interpretation –Multiple commands on a single line –Expansion of wildcard filenames –Redirection.
2000 Copyrigths Danielle S. Lahmani UNIX Tools G , Fall 2000 Danielle S. Lahmani Lecture 3.
23-Jun-15Advanced Programming Spring 2002 bash Henning Schulzrinne Department of Computer Science Columbia University.
CS 497C – Introduction to UNIX Lecture 36: - Customizing the Environment Chin-Chih Chang
More Shell Basics CS465 - Unix. Unix shells User’s default shell - specified in /etc/passwd file To show which shell you are currently using: $ echo $SHELL.
Guide To UNIX Using Linux Third Edition
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
Bash Shell Scripting 10 Second Guide Common environment variables PATH - Sets the search path for any executable command. Similar to the PATH variable.
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 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.
Introduction to Shell Script Programming
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.
Week 7 Working with the BASH Shell. Objectives  Redirect the input and output of a command  Identify and manipulate common shell environment variables.
Chapter 5 Bourne Shells Scripts By C. Shing ITEC Dept Radford University.
Chapter 6: Shell Programming
An Introduction to Unix Shell Scripting
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 Unix – CS 21 Lecture 9. Lecture Overview Shell description Shell choices History Aliases Topic review.
Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.
Introduction to Linux OS (IV) AUBG ICoSCIS Team Prof. Volin Karagiozov March, 09 – 10, 2013 SWU, Blagoevgrad.
Linux+ Guide to Linux Certification, Third Edition
Linux Operations and Administration
Basic Shell Scripting - Part 1 Objective - Learn to: Read Start-up Files Edit Start-up Files Modify Your User Environment Communicate with Users Write.
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.
Shell Programming. Introducing UNIX Shells  Shell is also a programming language and provides various features like variables, branching, looping and.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
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.
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.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
1 © 2000 John Urrutia. All rights reserved. Session 5 The Bourne Shell.
Customizing the Shell Environment. UNIX Shells Two characteristics of shells –Interactive: prompts ($) and waits for your response/requests –Noninteractive:
Chapter Six Introduction to Shell Script Programming.
Shell Control Statements and More
Agenda Positional Parameters / Continued... Command Substitution Bourne Shell / Bash Shell / Korn Shell Mathematical Expressions Bourne Shell / Bash Shell.
1 Unix/Linux commands and shell programming-Part 2 (Dr. Mohamed El Bachir Menai)
CSCI 330 UNIX and Network Programming Unit III Shell, Part 1.
Agenda The Bourne Shell – Part II Special Characters Ambiguous File Reference Variable Names and Values User Created Variables Read-only Variables (Positional.
Linux+ Guide to Linux Certification, Second Edition
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]
Linux Administration Working with the BASH Shell.
INTRODUCTION TO SHELL SCRIPTING By Byamukama Frank
1 Lecture 8 Shell Programming – Control Constructs COP 3353 Introduction to UNIX.
SUSE Linux Enterprise Desktop Administration
CSC 352– Unix Programming, Fall 2012
Shell Script Assignment 1.
UNIX and Shell Programming (06CS36)
Agenda Control Flow Statements Purpose test statement
Pepper (Help from Dr. Robert Siegfried)
John Carelli, Instructor Kutztown University
Shell Programming.
Linux Shell Script Programming
CSC 352– Unix Programming, Fall, 2011
Introduction to Bash Programming, part 3
Review.
Review The Unix Shells Graham Glass and King Ables,
Presentation transcript:

CS465 – Unix The Korn Shell (ksh)

ksh Shell The Korn (ksh) shell Scripting syntax is compatible with the standard Bourne (sh) shell Included in Unix operating systems from most vendors (Sun Solaris, SGI IRIX, Linux, etc.) Provides some extra features: Command aliasing Easier user input and math calculations Command history Command-line editing

Command Aliases Aliases allow you to define your own commands Format: $ alias [-x] name=definition Examples: $ alias ll="ls -la" $ alias dir="ls -F" $ alias –x home="cd;ls" $ alias –x rm="rm -i" Using the –x option “exports” the alias.

Command Aliases To remove aliases: To show all aliases: $ unalias name To show all aliases: $ alias If you put the alias commands in your .profile or .kshrc file, you can use them every time you login.

Displaying Alias Values To determine which command a specific alias will run, use either alias OR whence: $ alias ll="ls -la" $ alias ll ll='ls –la' $ whence ll ls –la $

The Dash (-) Character Dash (-) represents the previous working directory. When used to cd, it automatically displays the current directory path. Example: Switching between one of your subdirectories and the system bin directory: $ pwd /home/user1/sub1 $ cd /bin $ pwd /bin $ cd - /home/user1/sub1 $ cd - /bin $

The let command let provides built-in integer handling that easier to use and 10-30 times faster than expr Syntax: $ let math-expression NOTE: Use = to assign values Examples $ let i=i+1 $ let "prod = 12 * 6" Double quotes allow spaces and no backslash on *

The let command Can use (( instead of let )): x=3 y=4 ((z = x * y)) Result: z = 12 ((z = z + 1)) Result: z = 13 Notes: No dollar sign ($) needed to access variable values Double parentheses act as quotes, so you can add spaces and don’t need to backslash metacharacters

let Operators Integer operators: +, -, *, /, % Integer comparisons: <, <=, ==, !=, >=, > Compounds && (and), || (or), ! (not) NOTE: No backslashes needed inside (( ))

Bourne vs Korn Comparison Bourne Shell result=`expr calculation` (( result = calculation )) [ $num -ge 0 ] (( num >= 0 )) [ $num1 -gt 0 -a $num2 -lt 100 ] (( num1 > 0 && num2 < 100 )) Korn Shell

let example i=1 total=0 while (( i <= 100 )) do (( total = total + i )) (( i = i + 1 )) done echo $total

Korn Additional test Operators The Korn shell also extends the test expression from the Bourne shell. By using two sets of square brackets, instead of one set, the system uses the Korn shell (instead of Bourne) to test specific conditions. [[ test-condition ]]

Korn Additional test Operators File Operators: -a file file exists -L file file exists and is a symbolic link f1 -ef f2 file1 and file2 are linked f1 –nt f2 file1 is newer than file2 f1 –ot f2 file1 is older than file2 Logical operators: && logical AND || logical OR

Korn test example $ cat lsdir #! /bin/ksh # lists directory contents if yours if [[ -d $1 && -O $1 ]] then ls -l $1 else echo Error - not a directory or not yours! fi exit $

Command History The Korn shells supports a history feature that lets you recall previous commands, performing a substitution if necessary. The history command displays the previous 16 commands: $ history Common Alias: $ alias h="history"

r (recall/rerun command) r alone repeats the last command. r 11 repeats command number 11 r -2 repeats the command before the last one. r d repeats the last command that started with a “d”. r sort one=two repeats previous sort command using two instead one.

History Variables HISTFILE=$HOME/.myhist $HOME/.sh_history HISTSIZE=50 HISTFILE contains name of your history file HISTFILE=$HOME/.myhist If you do not provide a name, then the Shell uses: $HOME/.sh_history HISTSIZE contains how many commands to save Default (to save) is 128 (but show only last 16) HISTSIZE=50

In-Line Command Editing You can perform vi in-line editing of the command line In-line edit mode enables you to edit a previous command on the current command line Use vi commands to move and edit the previous command line

Turning On/Off Editing $ set [-+]o vi set -o vi turns command-line editing on set +o vi turns it off Once turned on, ESC key activates the in-line editor To use: Press the ESC key to activate in-line editing. Press – (or k) until the desired command appears. Edit using vi commands, then press ENTER.

Using Command Line Editing Your command line now becomes a single line editor window into the command history file. The single line you start viewing is the current Shell command line. You can move to other lines by using the editor move commands (- moves backwards, + moves forwards). Editor search commands can also be used to select the line being viewed.

Some vi for Command Line Editing <ESC> Enter command mode i/a Enter insert mode and add text before/after cursor l Move cursor right h Move cursor left fc Move to character c x Delete character dw Delete one word $ Move to end of line <Enter> Execute the command

Using Filename Completion Automated completion of a filename used as an argument to a command. To initiate, use the <ESC> key and a backslash Example: $ ls file1 file2 fileofstuff notes subdir whynot $ vi n<ESC>\ Uses vi to edit the file notes Note: Only works when file completion is unique

Filename Completion Choices If the filename is NOT unique, you can get a list of choices by using: <ESC>= Example: $ cat f<ESC>= 1) file1 2) file2 3) fileofstuff $ cat f_ Now when you press a number (1-3), that file is chosen and used to complete the command.

Additional Korn Shell Variables $PPID the shell's parent process' PID $_ last parameter of previous command $RANDOM randomly generated integer (0-Max) $ENV pathname of Korn shell environment startup file $OLDPWD working directory set before current one $EDITOR pathname of editor to use for line editing $PS3 prompt for select loops (default is #?) $TMOUT number of seconds to wait before exiting shell if no command is given

OLDPWD example $ pwd /home/smith123/cprogs $ cd /etc /etc $ cd $OLDPWD

New Pattern Matching ~ home directory ~username username’s home (equivalent to $HOME) ~username username’s home ~+ current working directory (equivalent to $PWD) ~- previous working directory (equivalent to $OLDPWD)

Using Tilde Substitution $ pwd /home/smith123/progs/cprogs $ cd /home/smith123 $ cd ~- $ cd ~jones456 /home/jones456

Reading User Input Korn shell provides one command that will BOTH “echo” and “read”: Syntax: $ read 'varname?prompt' Examples: $ read 'name?Enter your name: ' $ read 'year?Current year? '

read Example $ cat mul read 'num1?Enter a number: ' read 'num2?Enter another number: ' (( prod = num1 * num2 )) echo $num1 times $num2 is $prod $ $ mul Enter a number: 5 Enter another number: 8 5 times 8 is 40 $

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

until Example Read in a number from a user, and verify the number is positive. $ cat posnum #! /bin/sh # Read positive number from user num=0 until [ num -gt 0 ] do echo Enter a positive non-zero number: read num done echo You entered $num exit 0 $

until Example Read in a number from a user, and verify the number is positive. $ cat posnum #! /bin/sh # Read positive number from user num=0 until (( num > 0 )) do echo Enter a positive non-zero number: read num done echo You entered $num exit 0 $

until Example Execution $ posnum Enter a positive non-zero number: -50 12 You entered 12 $

select statement select var in list do command(s) done Implements a menu from within a loop. Automatically displays a numbered list of choices, and interpret the number that the user enters. Begin and end of command block defined by keywords do…done select var in list do command(s) done

select statement You must still use the case control structure to evaluate the choice chosen, but the structure will loop automatically unless you have chosen to exit. If your menu options consist of multiple words, they must be enclosed in double quotes.

select example $ cat junkit #!/bin/ksh # Menu-driven junkit script junk=$HOME/junkdir # # If junkdir directory doesn't exist, create it if [[ ! (-d $junk) ]] then 'mkdir' $junk fi select choice in "List junk" "Delete junk" "Junk files" "Exit" do case $choice in "List junk") ls -lgF $junk;;

select example NOTE: The break command is used to exit the loop. "Delete junk") rm $junk/*;; "Junk files") read 'filelist?Enter files to junk: ' mv $filelist $junk;; "Exit") break;; *) echo Invalid choice; please try again;; esac done exit 0 $ NOTE: The break command is used to exit the loop.

select execution $ pwd /export/home/jmsmith $ junkdir 1) List junk 2) Delete junk 3) Junk files 4) Exit #? 1 total 0 #? #? 3 Enter files to junk: p2.c #? #? 1 total 2 -rw------- 1 jwsmith 122 May 7 13:19 p2.c #? #? 2 #? 1 total 0 #? 4 $

Other Korn Additions: String Length Length of string: ${#varname} Returns length of string stored in variable Example: $ cat namelen name="Pam Smallwood" echo ${#name} $ namelen 13 $

Other Korn Additions Example: Forcing Command Execution In addition to the back quotes (graves) `command` In Korn you can use: $(command) Example: $ name=$(whoami) $ echo $name small000 $

Sample .kshrc file # Set command aliases alias rm='rm -i ' alias rename='mv ' alias c clear # Set environment variables PATH=$PATH:. PS1="$PWD[!] $ " EDITOR=vi # Export global variables export PATH EDITOR PS1 # Set history variables HISTSIZE=40

Default .profile Review handout

Capturing a Terminal Session You can capture what your terminal display to a file using the command script Syntax: $ script filename Everything that appears on your screen will be captured in the file, until you enter <ctrl-d>

Terminal Session Example $ script session1 Script started, file is session1 $ pwd /export/home/small000 $ date Thu May 22 19:34:25 MDT 2003 $ <CTRL-d> Script done, file is session1 $ $ cat session1 $ pwd /export/home/small000 $ date Thu May 22 19:34:25 MDT 2003 script done on Thu May 22 19:34:29 2003 $