bash Data Administrative Shell Scripting COMP2101 Fall 2017

Similar documents
Linux Shell Scripting. Linux System Administration COMP2018 Summer 2017

S E C T I O N O V E R V I E W

bash Tests and Looping Administrative Shell Scripting COMP2101 Fall 2017

bash Tests and Looping Administrative Shell Scripting COMP2101 Fall 2017

CS Unix Tools & Scripting

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

Shell scripting and system variables. HORT Lecture 5 Instructor: Kranthi Varala

Useful Unix Commands Cheat Sheet

CSE 391 Lecture 5. Intro to shell scripting

5/8/2012. Exploring Utilities Chapter 5

CMPS 12A Introduction to Programming Lab Assignment 7

Bash Programming. Student Workbook

EECS2301. Example. Testing 3/22/2017. Linux/Unix Part 3. for SCRIPT in /path/to/scripts/dir/* do if [ -f $SCRIPT -a -x $SCRIPT ] then $SCRIPT fi done

UNIX shell scripting

A shell can be used in one of two ways:

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

Using bash. Administrative Shell Scripting COMP2101 Fall 2017

CSE 390a Lecture 5. Intro to shell scripting

Output with printf Input. from a file from a command arguments from the command read

Shell Programming for System Administrators Student Guide

Shell Scripting. Todd Kelley CST8207 Todd Kelley 1

COMP 4/6262: Programming UNIX

Here redirection. Case statement. Advanced Unix Tools Lecture 6 CS214 Spring 2004 Friday March 5, 2004

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

System Programming. Session 6 Shell Scripting

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

Shells & Shell Programming (Part B)

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

System Programming. Unix Shells

Title:[ Variables Comparison Operators If Else Statements ]

BASH SHELL SCRIPT 1- Introduction to Shell

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

More Scripting Techniques Scripting Process Example Script

CSE 374 Programming Concepts & Tools. Brandon Myers Winter 2015 Lecture 4 Shell Variables, More Shell Scripts (Thanks to Hal Perkins)

BASH and command line utilities Variables Conditional Commands Loop Commands BASH scripts

Bash scripting Tutorial. Hello World Bash Shell Script. Super User Programming & Scripting 22 March 2013

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

5/20/2007. Touring Essential Programs

Getting to grips with Unix and the Linux family

Bourne Shell Reference

Week 5 Lesson 5 02/28/18

Assignment clarifications

Basic Linux (Bash) Commands

More Scripting Todd Kelley CST8207 Todd Kelley 1

1. Hello World Bash Shell Script. Last Updated on Wednesday, 13 April :03

4. Inputting data or messages to a function is called passing data to the function.

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

CSE 374: Programming Concepts and Tools. Eric Mullen Spring 2017 Lecture 4: More Shell Scripts

do shell script in AppleScript

INTRODUCTION TO SHELL SCRIPTING ITPART 2

22-Sep CSCI 2132 Software Development Lecture 8: Shells, Processes, and Job Control. Faculty of Computer Science, Dalhousie University

Haskell Scripts. Yan Huang

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

Lecture 4. Log into Linux Reminder: Homework 1 due today, 4:30pm Homework 2 out, due next Tuesday Project 1 out, due next Thursday Questions?

PERL Scripting - Course Contents

Unleashing the Shell Hands-On UNIX System Administration DeCal Week 6 28 February 2011

Log into Linux Reminders: Homework 1 due today; Homework 2 due on Thursday Questions?

C: How to Program. Week /Mar/05

Basic Shell Scripting

Pro Bash Programming. Scripting the GNU/Linux Shell. Second Edition. Jayant Varma. Chris F. A. Johnson. Hi mm mm. mmmm mmmm HHi

Shell Programming. Introduction to Linux. Peter Ruprecht Research CU Boulder

bash Execution Control COMP2101 Winter 2019

Manual Shell Script Linux If Not Equal String Comparison

UNIX Shell Programming

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

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

bash Scripting Introduction COMP2101 Winter 2019

Introduction to Supercomputing

IT 374 C# and Applications/ IT695 C# Data Structures

example: name1=jan name2=mike export name1 In this example, name1 is an environmental variable while name2 is a local variable.

Chapter 2 - Introduction to C Programming

Bourne Shell (ch 8) Overview. Bourne Shell. Bourne Shell. Bourne Shell. Bourne Shell. Redirect standard error. Redirect standard error

CSCI 2132: Software Development. Norbert Zeh. Faculty of Computer Science Dalhousie University. Shell Scripting. Winter 2019

Shells and Shell Programming

Basic Shell Scripting Practice. HPC User Services LSU HPC & LON March 2018

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

Introduction to Bash Programming. Dr. Xiaolan Zhang Spring 2013 Dept. of Computer & Information Sciences Fordham University

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

Shell Programming (bash)

Environment Variables

Introduction to Perl. c Sanjiv K. Bhatia. Department of Mathematics & Computer Science University of Missouri St. Louis St.

Shells and Shell Programming

LINUX Scripts de Bash Shell. Exercise 1 - Working with Files

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Chapter 2: Overview of C++

The UNIX Shells. Computer Center, CS, NCTU. How shell works. Unix shells. Fetch command Analyze Execute

Introduction to UNIX Part II

Advanced Unix Programming Module 03 Raju Alluri spurthi.com

QUESTION BANK ON UNIX & SHELL PROGRAMMING-502 (CORE PAPER-2)

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

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 2: Using Data

UNIX II:grep, awk, sed. October 30, 2017

Programming Languages & Translators. XML Document Manipulation Language (XDML) Language Reference Manual

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?

Vi & Shell Scripting

Shell Programming Overview

9.2 Linux Essentials Exam Objectives

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

Linux shell scripting Getting started *

Transcription:

bash Data Administrative Shell Scripting COMP2101 Fall 2017

Variables Every process has memory-based storage to hold named data A named data item is referred to as a variable (sometimes called a parameter), all of them together create a simple table with names and values Variables can hold text or binary data as their value Variables are typically created by assigning data to them, using an assignment operator such as = myvar=3 variable2="string data" vowels="aeiou"

Variables Variable content is accessed using the $ symbol prefixed to the variable name Non-trivial variable names must be surrounded by { } echo $myvar echo ${myvar} echo ${myarray[32]} echo ${frank-n["beans"]}

Environment Variables By default variables are created in local process memory, not in the process environment Environment variables are inherited by child processes Environment variables are normally named using capital letters and numbers only Variables can be exported to the environment or removed from the environment VARNAME= Some data for this variable export VARNAME export -n VARNAME export VARNAME= Data

Using Variables Variables have many uses Command line substitution is a very common use, using a variable to provide data used on a command line Variables are deleted using the unset command echo $SHELL ls $HOME for file in $FILES; do if [ $USER!= $LOGNAME ] mypid=$$ unset VAR

Getting Data For Variables A very common way to get dynamic data into a variable is to use the `` or $() syntax to obtain the output of a command Interactive input can be saved in a variable using the read command today=`date +%A` today=$(date +%A) echo $today read myvar read -p "Give me a number " mynum echo "You gave me $mynum"

Exercises Create an environment variable on your command line named MYNAME and assign your name to it as data Create a local variable on your command line named mytitle and assign a title you like to it as data, such as Mister, Miss, Doctor, President, etc. Use the echo command to print out your name preceded by your title, using your variables to supply the data Create a script with the echo command from the previous step and run it Modify your script to print out: Welcome to planet hostname, title name! Today is weekday.

Shell Data - Numbers Data is often found inline in scripts Inline data can be simple numbers or strings of characters Numbers are simply entered as digits and can be signed, but must be integers bash can do basic arithmetic +, -, *, /, % on integers by putting arithmetic statements inside $(( )) Leaving off the $ allows you to test if the result is zero echo 32 echo $(( 3 + 4 )) echo "5 divided by 2 leaves a remainder of $(( 5 % 2 ))" (( $loot % $raiders )) echo "Uh-oh, doesn't divide evenly" echo "$(( $RANDOM % 6 + 1 )) is a random roll of a die"

Working with Numbers The $((expression)) syntax assumes normal order of operations (i.e. first %*/, then +-, all from left to right) Parentheses can be used inside the arithmetic expression to change the order awk can do floating point (e.g. awk 'BEGIN {printf "%.2f\n", 7/3}') So can bc (e.g. bc <<< "6.7*1.2") read -p "Give me 2 numbers: " firstnum secondnum echo "$firstnum plus $secondnum is $((firstnum + secondnum))" echo "$firstnum minus $secondnum is $((firstnum - secondnum))" echo "$firstnum times $secondnum is $((firstnum * secondnum))" echo "$firstnum divided by $secondnum is $((firstnum / secondnum))" echo It is also $(awk "BEGIN{printf \"%.2f\", $firstnum/$secondnum}") echo "The remainder when dividing $firstnum by $secondnum is $((firstnum % secondnum))" echo "$firstnum to the power of $secondnum is $(bc <<< "$firstnum ^ $secondnum")"

Shell Data - Strings Strings are normally entered as single words, or surrounded by quotes for strings containing special characters such as spaces Single quotes turn off all special characters Double quotes turn off most special characters, $ is still special inside "" Special characters can also be preceded with \ to turn off their special meaning cd touch My File ls touch "My File" ls touch My\ Other\ File ls touch 'Terrible"Name"' ls touch -- '-worse\ name' ls

Working With Strings Several cli tools are available to parse and manipulate strings ${#varname} will give the length of the string expr index string searchtext will return a non-zero index value if searchtext is in string [fe]grep, tr, cut, sed, [ng]awk - ref. course resources See http://tldp.org/ldp/abs/html/string-manipulation.html for more pure bash string manipulation techniques and information

bash Prompts Prompts are displayed to help users determine what is going on and what is expected of them bash stores prompt formats in 4 variables and displays them when appropriate PS1 has the prompt to let a user know that bash is expecting a command ($ vs. # convention indicates privilege level) PS2 has the prompt to let a user know more input is expected for the current command line PS3 is used for the select command PS4 is used to prefix an output line during execution tracing See PROMPTING section of bash man page for more info

Exercises Enter an echo command using quotes which start on one line and end on another Enter a pipeline command that starts on one line and ends on another Enter a command with backslash at the end of the line Use a HERE document to create a file named food with four lines of text, each containing a food name

Predefined Variables bash provides a number of variables containing useful information, the env command will display them Some are inherited from ancestor processes (e.g. login, getty, init) More are often set up by user environment files to customize the user experience bash also has some special variables that dynamically retrieve data for realtime uses

Special Variables $ - current process id # - number of parameters on the command line of a script 0-n - command line parameters RANDOM - a random 15-bit integer REPLY - default variable name for the read command? - exit status of most recent command

Complex Variables Arrays can be created using ( ) They allow us to group data items and still operate on them as individual items Elements of an array are uniquely identified by an index integer starting at 0 Elements of an array can be accessed using the varname[index] syntax Negative indices count backwards from the end of the array @ and * can be used as indices to include all array elements # can be used to obtain a count of elements in an array arrayvar=(a b c) echo ${arrayvar[0]} ${arrayvar[-1]} echo ${arrayvar[@]} ${#arrayvar[@]} INDEX DATA 0 a 1 b 2 c

Associative Arrays Associative arrays (sometimes called hashes) can use any string as an index They must be declared before being used They are useful for storing structured data declare A foo foo=([key1]= data1 [key2]= data2 ) echo ${foo[key1]} echo ${foo[@]} echo ${!foo[@]} INDEX key1 key2 DATA data1 data2

Exercises Create an array named colours and give it the following data values: red, green, blue Create a hash named animals and give it the following data elements: key red - value cardinal, key green - value frog, key blue - value lobster Use echo to display all the elements of the colours array, both by using the index values, and by using @ as an index Do the same for the same for the animals array Create a variable named num and give it a value of 0 Use echo to display the data from the colours array corresponding to the value of $num followed by the value from the animals hash which uses the colour from the colours array as a key to find an animal name e.g. red cardinal, green frog, blue lobster Create a script to define the array and hash as above, and ask the user for a number for the num variable to select a combination to print out Test your script to show you can make it print any valid combination from your array

Command Line Arguments Any command can have options and arguments, although some commands do not The command line is accessible in a program or script, using the special variables $0, $1, $2, etc. $0 holds the command itself (there are exceptions to this) $1, $2, $3, etc. hold each of the remaining words of the command line On a bash command line, words are space-separated sequences of characters Quoting and the escape character can be used to turn off the word separation of any particular space on a command line