Bash Programming. Student Workbook

Similar documents
Advanced UNIX Tools. Student Workbook

Assignment clarifications

5/20/2007. Touring Essential Programs

UNIX System Programming Lecture 3: BASH Programming

A shell can be used in one of two ways:

bash Args, Signals, Functions Administrative Shell Scripting COMP2101 Fall 2017

UNIX shell scripting

12.1 UNDERSTANDING UNIX SHELL PROGRAMMING LANGUAGE: AN INTRODUCTION Writing a Simple Script Executing a Script

Table of contents. Our goal. Notes. Notes. Notes. Summer June 29, Our goal is to see how we can use Unix as a tool for developing programs

CSCI 211 UNIX Lab. Shell Programming. Dr. Jiang Li. Jiang Li, Ph.D. Department of Computer Science

Implementation of a simple shell, xssh

Linux shell scripting Getting started *

Welcome to the Bash Workshop!

Shells. A shell is a command line interpreter that is the interface between the user and the OS. The shell:

Today. Review. Unix as an OS case study Intro to Shell Scripting. What is an Operating System? What are its goals? How do we evaluate it?

Creating a Shell or Command Interperter Program CSCI411 Lab

5/8/2012. Specifying Instructions to the Shell Chapter 8

Shell Scripting. With Applications to HPC. Edmund Sumbar Copyright 2007 University of Alberta. All rights reserved

Review of Fundamentals

CS 25200: Systems Programming. Lecture 10: Shell Scripting in Bash

Unix Scripts and Job Scheduling. Overview. Running a Shell Script

The Online Unix Manual

The Unix Shell & Shell Scripts

Shells and Shell Programming

Welcome to the Bash Workshop!

85321, Systems Administration Chapter 6: The shell

UNIX Shell Programming

Exploring UNIX: Session 3

Introduction to UNIX. Logging in. Basic System Architecture 10/7/10. most systems have graphical login on Linux machines

Bourne Shell Programming Topics Covered

28-Nov CSCI 2132 Software Development Lecture 33: Shell Scripting. 26 Shell Scripting. Faculty of Computer Science, Dalhousie University

Unix as a Platform Exercises + Solutions. Course Code: OS 01 UNXPLAT

9.2 Linux Essentials Exam Objectives

CHAPTER 3 SHELL PROGRAMS: SCRIPTS

Bashed One Too Many Times. Features of the Bash Shell St. Louis Unix Users Group Jeff Muse, Jan 14, 2009

bash Args, Signals, Functions Administrative Shell Scripting COMP2101 Fall 2018

EECS2301. Lab 1 Winter 2016

CSC UNIX System, Spring 2015

Lab 2: Linux/Unix shell

Unix/Linux Basics. Cpt S 223, Fall 2007 Copyright: Washington State University

CSC209H Lecture 1. Dan Zingaro. January 7, 2015

Review of Fundamentals. Todd Kelley CST8207 Todd Kelley 1

Bourne Shell Reference

C++ Programming for Non-C Programmers. Supplement

Essentials for Scientific Computing: Bash Shell Scripting Day 3

System Programming. Unix Shells

Unix as a Platform Exercises. Course Code: OS-01-UNXPLAT

Command Interpreters. command-line (e.g. Unix shell) On Unix/Linux, bash has become defacto standard shell.

Essential Unix (and Linux) for the Oracle DBA. Revision no.: PPT/2K403/02

Contents. Note: pay attention to where you are. Note: Plaintext version. Note: pay attention to where you are... 1 Note: Plaintext version...

Shells and Shell Programming

ACS Unix (Winter Term, ) Page 21

COMS 6100 Class Notes 3

Getting started with Hugs on Linux

Getting started with Hugs on Linux

Standard. Shells. tcsh. A shell script is a file that contains shell commands that perform a useful function. It is also known as shell program.

Shell script/program. Basic shell scripting. Script execution. Resources. Simple example script. Quoting

Answers to AWK problems. Shell-Programming. Future: Using loops to automate tasks. Download and Install: Python (Windows only.) R

1. What statistic did the wc -l command show? (do man wc to get the answer) A. The number of bytes B. The number of lines C. The number of words

Title:[ Variables Comparison Operators If Else Statements ]

Linux shell programming for Raspberry Pi Users - 2

Implementation of a simple shell, xssh

Basics. I think that the later is better.

Review of Fundamentals. Todd Kelley CST8207 Todd Kelley 1

More Scripting Todd Kelley CST8207 Todd Kelley 1

Shell Scripting. Todd Kelley CST8207 Todd Kelley 1

Appendix A GLOSSARY. SYS-ED/ Computer Education Techniques, Inc.

Chapter-3. Introduction to Unix: Fundamental Commands

Examples: Directory pathname: File pathname: /home/username/ics124/assignments/ /home/username/ops224/assignments/assn1.txt

CS Unix Tools. Lecture 3 Making Bash Work For You Fall Hussam Abu-Libdeh based on slides by David Slater. September 13, 2010

Writing Shell Scripts part 1

Shell scripting Scripting and Computer Environment - Lecture 5

Basic Linux (Bash) Commands

CS Fundamentals of Programming II Fall Very Basic UNIX

bash, part 3 Chris GauthierDickey

Vi & Shell Scripting

Cisco IOS Shell. Finding Feature Information. Prerequisites for Cisco IOS.sh. Last Updated: December 14, 2012

Introduction p. 1 Who Should Read This Book? p. 1 What You Need to Know Before Reading This Book p. 2 How This Book Is Organized p.

Unix Internal Assessment-2 solution. Ans:There are two ways of starting a job in the background with the shell s & operator and the nohup command.

Unix Introduction to UNIX

Linux File System and Basic Commands

Chapter 4. Unix Tutorial. Unix Shell

Introduction to Linux (Part I) BUPT/QMUL 2018/03/14

COMP 4/6262: Programming UNIX

Using echo command in shell script

C++ Programming for Non-C Programmers. Supplement

Unix Shell scripting. Dr Alun Moon 7th October Introduction. Notation. Spaces

Lezione 8. Shell command language Introduction. Sommario. Bioinformatica. Mauro Ceccanti e Alberto Paoluzzi

Appendix B WORKSHOP. SYS-ED/ Computer Education Techniques, Inc.

Exploring UNIX: Session 5 (optional)

Shell Scripting. Jeremy Sanders. October 2011

Crash Course in Unix. For more info check out the Unix man pages -orhttp:// -or- Unix in a Nutshell (an O Reilly book).

Perl and R Scripting for Biologists

Session 1: Accessing MUGrid and Command Line Basics

Linux Shell Scripting. Linux System Administration COMP2018 Summer 2017

Lab #12: Shell Scripting

LING 408/508: Computational Techniques for Linguists. Lecture 5

Introduction to UNIX Shell Exercises

Introduction to Unix: Fundamental Commands

A Brief Introduction to Unix

Transcription:

Student Workbook

Bash Programming Published by ITCourseware, LLC, 7245 South Havana Street, Suite 100, Englewood, CO 80112 Contributing Authors: Julie Johnson, Rob Roselius Editor: Jeff Howell Special thanks to: Many Shell instructors whose ideas and careful review have contributed to the quality of this workbook, including Brandon Caldwell, Roger Jones, Jim McNally, and Bill Parette, and the many students who have offered comments, suggestions, criticisms, and insights. Copyright 2002 by ITCourseware, LLC. All rights reserved. No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage retrieval system, without permission in writing from the publisher. Inquiries should be addressed to ITCourseware, LLC, 7245 South Havana Street, Suite 100, Englewood, CO 80112. (303) 302-5280. All brand names, product names, trademarks, and registered trademarks are the property of their respective owners. Page ii Rev 1.1.3 2002 ITCourseware, LLC

Contents Chapter 1 - Course Introduction... 7 Course Objectives... 8 Course Overview... 10 Using the Workbook... 11 Suggested References and Reading... 12 Chapter 2 - UNIX Processes... 15 What is a Process?... 16 Process Structure... 18 The ps Utility... 20 Options to the ps Utility... 22 Background Commands (&)... 24 Killing Background Processes... 26 Redirecting the Standard Error... 28 Labs... 30 Chapter 3 - Getting Started... 33 What is a Shell?...34 Running Scripts... 36 Specifying the Script's Interpreter... 38 The PATH Environment Variable... 40 Sub-shells... 42 Labs... 44 Chapter 4 - Variables... 47 Shell Variables... 48 The read Command... 50 The export Command... 52 The Shell Environment... 54 Parameter Expansion... 56 Command Substitution... 58 Labs... 60 2002 ITCourseware, LLC Rev 1.1.3 Page iii

Chapter 5 - The Login Process... 63 The Login Process... 64 The System Profile Script... 66 Your.bash_profile Script... 68 The. Command...70 Labs... 72 Chapter 6 - Conditional Statements... 75 The Exit Status of Commands... 76 Command Line Examples... 78 The test Command... 80 The if-then-else Construct... 82 The elif Construct... 84 case Statements...86 Labs... 88 Chapter 7 - Loops... 91 The for Loop... 92 The while Loop... 94 break and continue... 96 Reading Lines From Files... 98 Using Arrays with Loops... 100 Labs... 102 Chapter 8 - Special Variables... 105 $$ - PID of Shell... 106 Command-Line Arguments... 108 $# - Number of Arguments... 110 $* - All Arguments... 112 The shift Command... 114 The set Command... 116 Getting Options... 118 Labs... 120 Page iv Rev 1.1.3 2002 ITCourseware, LLC

Chapter 9 - Quoting Mechanisms... 123 Single vs. Double Quotes... 124 What is a Here Document?... 126 Using a Here Document... 128 Here Document Quoting... 130 Ignoring Leading Tabs... 132 Labs... 134 Chapter 10 - Functions... 137 Shell Functions... 138 Passing Arguments to Functions... 140 Returning Values from Functions... 142 Function Declarations... 144 Labs... 146 Chapter 11 - Advanced Programming... 149 Shell Arithmetic... 150 The select Statement... 152 Terminal Independence in Scripts... 154 The eval Command... 156 Labs... 158 Chapter 12 - Debugging Techniques... 161 Using echo... 162 Using Standard Error... 164 Script Tracing... 166 Options for Debugging... 168 Conditional Debugging... 170 Labs... 172 Solutions - Bash Programming... 175 Index... 193 2002 ITCourseware, LLC Rev 1.1.3 Page v

Page vi Rev 1.1.3 2002 ITCourseware, LLC

Chapter 4 Variables Chapter 4 - Variables Objectives Create and use shell variables on the command line and in scripts. Write shell scripts that interact with users by displaying prompts and reading their response. Pass variables from parent to child scripts using environment variables. Capture the output of a command and store it in a variable or use it as parameters to another command. Use variable substitution. 2002 ITCourseware, LLC Rev 1.1.3 Page 47

Shell Variables Variables (also called parameters) are set with the equal sign binary operator. The value of a variable is retrieved with the dollar sign unary operator. Command line example: myname=bobo echo $myname bobo echo myname myname # Same as: echo bobo $name dereferences (i.e., returns the value of) the variable name. Don t put spaces or tabs before or after the equal sign in name=value. Page 48 Rev 1.1.3 2002 ITCourseware, LLC

Chapter 4 Variables Shell variables (called parameters in the manual) are variables much like those found in any programming language. Their values are always stored as strings, but there are mathematical operators in the shell language that will convert variables to numbers for calculations. Nearly all scripts use variables. The term binary operator on the facing page means that the equal sign operator takes two operands: the name of a variable on the left, and the variable s intended value on the right. The term unary operator means that the dollar sign takes only one operand, the name of a variable. Consider once more the following: echo $myname bobo What really happens is that the shell substitutes the value of myname for $myname right on the command line, before executing the echo command. The dollar sign tells the shell to look at the value of the variable myname and then replace $myname with bobo. That is to say, change to echo $myname echo bobo before executing the echo command. This is known parsing the command line. The echo command never saw a $, never saw myname, never saw $myname. All echo saw was bobo. 2002 ITCourseware, LLC Rev 1.1.3 Page 49

The read Command The read command allows you to prompt for input and store it in a variable. nameit2 echo -n "Enter your name: " read name echo "Did you parents actually pick $name for you?" del echo -n "Enter name of file to delete: " read file echo "Type 'y' to remove it, 'n' to change your mind..." rm -i $file echo "That was YOUR decision!" The -n option to echo omits the final newline character. Page 50 Rev 1.1.3 2002 ITCourseware, LLC

Chapter 4 Variables When it executes a read command, the shell script will pause, waiting for the user to type something on the keyboard. When the user types something and then presses <Enter>, whatever typed goes into the variable whose name appears to the right of read. When assigning a value to a variable with the read command, notice that the $ is not used. You only use a $ when you wish to substitute the value of a variable on a line, not when assigning it with read or =. Like this: read name NOT like this: read $name < Don t attempt to read into variables like this!!! Try it: echo "Line 1 here\n and line 2 here\n" echo "\n\n\n\n\n\n" 2002 ITCourseware, LLC Rev 1.1.3 Page 51

The export Command The export command puts a variable into the environment so it will be accessible to child processes. Try this on the command line: x=hello sh echo $x exit export x sh echo $x hello exit # Run a child shell. # Nothing in x. # Return to parent. # It's there. If the child modifies x, it will not modify the parent s original value. Verify this by doing the above commands again, but this time change x in the child and then display it when back in the parent. By convention, exported variables are in all CAPS. Page 52 Rev 1.1.3 2002 ITCourseware, LLC

Chapter 4 Variables Since UNIX is a multitasking operating system, many processes (jobs) can execute concurrently. It is very common to write shell scripts that fire off children to do specific tasks in parallel. A primary mechanism for communicating information from the parent to the child is through environment variables. This allows parameterization of children. 2002 ITCourseware, LLC Rev 1.1.3 Page 53

The Shell Environment The environment is a list of name-value pairs that is passed to the child program. Variables that are not in the environment are not passed to children. The export command puts variables into the environment. set... # Show values of all variables. env # Show environment variables only.... myname=mary export myname env # Look at environment now.... Page 54 Rev 1.1.3 2002 ITCourseware, LLC

Chapter 4 Variables When you run set or env, you see several variables that you know you didn t set. So who did? Answer: the shell. There are several predefined variables that the shell creates and sets when you log in. They are used by the shell and can also be used by you and your shell scripts. A few of them are shown here (see ksh for more): HOME PATH The default argument (home directory) for cd. The search path for commands. It is a colon-separated list of directories that are searched when you type a command. PS1 Primary prompt string, whose default is $. PS1 means Prompt String 1. PS2 Secondary prompt string, whose default is >. SECONDS BASH Number of seconds since the shell was invoked. Pathname of instance of shell you are running. Try it: echo $HOME 2002 ITCourseware, LLC Rev 1.1.3 Page 55

Parameter Expansion Parameters can be tested and manipulated with ${...} operations. Following are several substitution mechanisms: ${#parameter} ${parameter:-word} ${parameter:=word} ${parameter:?word} ${parameter:+word} ${parameter#pattern} ${parameter##pattern} ${parameter%pattern} ${parameter%%pattern} Length of parameter. If parameter is set and non-null, substitute it; else substitute word. If parameter is not set or is null, set it to word; substitute value of parameter. If parameter is set and non-null, substitute it; else print word and exit shell. If parameter is set and non-null, substitute word; else substitute nothing. See bash(1). Page 56 Rev 1.1.3 2002 ITCourseware, LLC

Chapter 4 Variables These parameter substitution mechanisms are very powerful and can make your code quite compact. Several of them are very useful for setting default values or printing error messages. Don t worry about using them a lot right now; you may find it easier to write the same functionality in your scripts with more conventional (although lengthier) if then else constructs. But even if you don t use these parameter substitution mechanisms yourself, you will run into existing scripts that do use them, and you need to be able to understand what they do. Example scripts: 1. # If the variable BACKUPPATH is defined in the # environment, use it, otherwise use $HOME/.backup Backup_path=${BACKUPPATH:-$HOME/.backup} cp -r * $Backup_path 2. # Extract the name of file $1 minus the. extension File=${1%.*} # $1 is positional arg 1 in a script 2002 ITCourseware, LLC Rev 1.1.3 Page 57

Command Substitution The stdout of a command can be captured and stored in a variable by using command substitution. When you enclose a command in grave accent marks (a.k.a. back-ticks), the shell replaces the command (and the graves) with the command s output. Example 1: here=`pwd` #Graves, not single quotes. cd /a/long/way/away pwd /a/long/way/away echo $here /home/s3/scripts cd $here pwd /home/s3/scripts Example 2: num=`who wc -l` echo $num 7 Page 58 Rev 1.1.3 2002 ITCourseware, LLC

Chapter 4 Variables You may also perform command substitution with $( ). Example: here=$(pwd) echo $here num=$(who wc - l) echo $num 2002 ITCourseware, LLC Rev 1.1.3 Page 59

Labs Write a script that prompts for your first name and reads it into a variable, then prompts for your last name and reads it into another variable, then displays your name in the format last, first. (Solution: showname) If your PS1 environment variable is set to PS1='${PWD#${HOME}/}-->', how would it affect your prompt? (Solution: PS1_ques) Write a script that tells how many people are logged on. The output should look something like this: There are 5 users currently logged on. (Solution: logger1) Make a directory in your home directory called bin. Move one of your executable shell scripts into your bin directory. Now edit.profile so that your bin directory (e.g., $HOME/bin) is added to your PATH variable. Log out and back in, then while still in your home directory, run the script that is in the bin directory. (Solution: bin_ex) What happens (if anything) when you set your environment variable HOME to /tmp, then do a cd? (Solution: HOME_ex) What happens (if anything) when you set your environment variable PATH to /tmp, then do an ls? (Solution: PATH_ex) Page 60 Rev 1.1.3 2002 ITCourseware, LLC

Chapter 4 Variables 2002 ITCourseware, LLC Rev 1.1.3 Page 61

Page 62 Rev 1.1.3 2002 ITCourseware, LLC