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

Similar documents
CS Unix Tools & Scripting

Bash scripting basics

Useful Unix Commands Cheat Sheet

Shell. SSE2034: System Software Experiment 3, Fall 2018, Jinkyu Jeong

sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi

Computer Systems and Architecture

Computer Systems and Architecture

Shells & Shell Programming (Part B)

Lab 4: Shell scripting

Vi & Shell Scripting

Shell programming. Introduction to Operating Systems

COMP 4/6262: Programming UNIX

Programming introduction part I:

Bourne Shell Reference

Shells and Shell Programming

Linux Shell Scripting. Linux System Administration COMP2018 Summer 2017

Shells and Shell Programming

Title:[ Variables Comparison Operators If Else Statements ]

Scripting. More Shell Scripts. Adapted from Practical Unix and Programming Hunter College

Advanced Unix Programming Module 03 Raju Alluri spurthi.com

Basic Linux (Bash) Commands

A shell can be used in one of two ways:

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

Conditional Control Structures. Dr.T.Logeswari

bash Tests and Looping Administrative Shell Scripting COMP2101 Fall 2017

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

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

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

Control Structures. CIS 118 Intro to LINUX

bash Execution Control COMP2101 Winter 2019

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

EECS 470 Lab 5. Linux Shell Scripting. Friday, 1 st February, 2018

Shell Programming (bash)

EECS2301. Special variables. $* and 3/14/2017. Linux/Unix part 2

9.2 Linux Essentials Exam Objectives

Linux shell programming for Raspberry Pi Users - 2

More Scripting Techniques Scripting Process Example Script

bash Tests and Looping Administrative Shell Scripting COMP2101 Fall 2017

Introduction to Linux Basics Part II. Georgia Advanced Computing Resource Center University of Georgia Suchitra Pakala

SHELL SCRIPT BASIC. UNIX Programming 2014 Fall by Euiseong Seo

UNIX shell scripting

Basic Shell Scripting

Bash shell programming Part II Control statements

INd_rasN SOME SHELL SCRIPTING PROGRAMS. 1. Write a shell script to check whether the name passed as first argument is the name of a file or directory.

Unix Guide. Meher Krishna Patel. Created on : Octorber, 2017 Last updated : December, More documents are freely available at PythonDSP

Grep and Shell Programming

What is Bash Shell Scripting?

SHELL SCRIPT BASIC. UNIX Programming 2015 Fall by Euiseong Seo

Shell Programming (Part 2)

Shell Scripting. Todd Kelley CST8207 Todd Kelley 1

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

Last Time. on the website

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

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

Програмиранев UNIX среда

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

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

Mills HPC Tutorial Series. Linux Basics II

Part 1: Basic Commands/U3li3es

Parameter searches and the batch system

Practice 5 Batch & Shell Programming

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

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

Manual Shell Script Linux If Not Equal String Comparison

Lecture 5. Essential skills for bioinformatics: Unix/Linux

OPERATING SYSTEMS LAB LAB # 6. I/O Redirection and Shell Programming. Shell Programming( I/O Redirection and if-else Statement)

Assignment 3, Due October 4

Prof. Navrati Saxena TA: R. Sachan Bharat Jyoti Ranjan

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

Php Scripts If Then Else Linux Bash Shell

UNIX System Programming Lecture 3: BASH Programming

LOG ON TO LINUX AND LOG OFF

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

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

While Statement Examples. While Statement (35.15) Until Statement (35.15) Until Statement Example

UNIX Shell Programming

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

Windshield. Language Reference Manual. Columbia University COMS W4115 Programming Languages and Translators Spring Prof. Stephen A.

Assignment clarifications

More Scripting and Regular Expressions. Todd Kelley CST8207 Todd Kelley 1

Linux Bash Shell Scripting

Perl. Many of these conflict with design principles of languages for teaching.

Multiple Choice - 42 Questions - 10 of 20%

"Bash vs Python Throwdown" -or- "How you can accomplish common tasks using each of these tools" Bash Examples. Copying a file: $ cp file1 file2

Perl. Perl. Perl. Which Perl

A Hands-On Tutorial: RNA Sequencing Using High-Performance Computing

Shell Script Example. Here is a hello world shell script: $ ls -l -rwxr-xr-x 1 horner 48 Feb 19 11:50 hello* $ cat hello #!/bin/sh

Quick Guide for the Torque Cluster Manager

UNIX Shell Scripts. What Is a Shell? The Bourne Shell. Executable Files. Executable Files: Example. Executable Files (cont.) CSE 2031 Fall 2012

Working with Shell Scripting. Daniel Balagué

Linux 系统介绍 (III) 袁华

Using bash. Administrative Shell Scripting COMP2101 Fall 2017

Shell Programming Overview

Bourne Shell Programming Topics Covered

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?

There are some string operators that can be used in the test statement to perform string comparison.

COMP 2718: Shell Scripts: Part 2. By: Dr. Andrew Vardy

CSC 2500: Unix Lab Fall 2016

Bash Shell Programming Helps

Shell Control Structures

Transcription:

Introduction to Linux Shell Programming Peter Ruprecht peter.ruprecht@colorado.edu www.rc.colorado.edu

Downloadable Materials Slides and examples available at https://github.com/researchcomputing/ Final_Tutorials/ (BashProg directory) 2

Outline Quoting Variables Tests and conditionals Decisions Arguments Loops Functions Alternative scripting languages 3

Overview All Linux shells have built-in programming elements; bash is very feature rich Can program directly on the terminal command line or in script files Shell scripts should start with the definition of the shell used to interpret subsequent shell commands: #/path/to/shell e.g., #/bin/bash 4

Variables Shell variables are local Traditionally lower case Environment variables are global, set using export Traditionally upper case Use. or source to return a variable to the parent shell $VAR is the value of the variable Variables can hold -D arrays: city[0]=juneau city[]=wasilla echo ${city[]} 5

Quoting string take string literally $MYVAR allow variable interpolation `cmd` - string output from command { } delimits variable names export NOW=`date +%Y%m%d` touch data2.${now}.dat 6

Tests and Conditions Put test condition in [] String comparison [ string = string2 ] [ string = string2 ] [ string =~ string2 ] (string contains string2) Spaces are important 7

Tests (continued) Integer comparison [ num eq num2 ] -ne (not equal), -gt (greater than), -ge (greater or equal), -lt (less than), -le (less or equal) Use bc to compare non-integers [ `echo $a>$b bc` = ] 8

Tests (still continued) Compound tests with && (AND) or (OR) go in [[ ]] [[ s = s2 && n ge n2 ]] Don t need [] if testing a return code: if rm file.txt; then echo Remove Failed fi 9

Arguments It s often useful to pass arguments to a shell script $ denotes the first argument, $2 the second, up to ${99} $* (all arguments, as a single word) $@ (all arguments, as individual words) $# (total number of arguments) $0 (name of script) 0

Arguments (continued) Example: #/bin/bash if [ $# -ge ]; then # reminder: $# is number of args echo File types: file $@ echo echo Number of lines: wc l $@ else echo Usage: $0 file [ filen] fi

Decisions if / then / else if [ test ] then command(s) elif [ test2 ] then command(s) else command(s) fi 2

Decisions (continued) #/bin/bash if [ $ -gt 0 ]; then echo $ is positive elif [ $ -eq 0 ]; then echo $ is zero else echo $ is negative fi 3

Decisions (continued) case case $variable in value) action ;; value2) action2 ;; value3 value4) action3 ;; *) default action ;; esac 4

Loops while while [ test ]; do commands done for for variable in list; do commands done (when used in for or while loops, the continue and break commands will, respectively, immediately start the next iteration of the loop or exit the loop) 5

while loop examples c=-40 echo Celsius Fahrenheit while [ $c le 40 ]; do echo $c `echo scale=3;(9/5)*$c+32 bc` c=`expr $c + ` #increment c by # c=$((c+)) #alternate increment syntax done cat myfile \ while read line; do if [[ $line =~ data ]]; then echo $line awk {print $3, $2*3.4} fi done 6

for loop examples for guy in Tom Dick Harry; do echo $guy is my buddy done for i in {0..0..2}; do echo $i is an even number done for f in *.txt; do now=`date +%Y-%m-%d-%H-%M` cat $f sed s/unix/unix/g > ${f}_$now done 7

Functions If a script needs to do the same task in several places, create a function. function_name () { commands; } 8

Function example send_email () { echo Directory $dir is $stat \ mail -s size check me@colorado.edu return 0; } for dir in /data /home; do pct=`df $dir grep $dir \ awk '{print $5}' cut -d% -f` if [ $pct -gt 90 ]; then stat= full send_email else stat= ok send_email fi done 9

HPC example #/bin/bash # set up parameter and batch files for a set of cluster # runs, then submit those jobs to the queue xmax=30 ymax=20 x=0 while [ $x -le $xmax ] ; do y=0 # need to reinitialize y each time thru the x loop while [ $y -le $ymax ] ; do # use "here document" to create parameter file cat > param_${x}_${y} <<ENDofDOC $x $y 3700 output_${x}_${y} ENDofDOC # use "echo" commands to create batch scripts; compare with here document method echo "#/bin/bash" > batch_${x}_${y} echo "#PBS -N ${x}_${y}" >> batch_${x}_${y} echo "#PBS -l nodes=3:ppn=8" >> batch_${x}_${y} echo 'cd $PBS_O_WORKDIR' >> batch_${x}_${y} echo "./my_prog.x < param_${x}_${y}" >> batch_${x}_${y} #submit job qsub -q queue batch_${x}_${y} y=$((y+5)) # increment y done # repeat inner loop over y x=$((x+0)) # increment x done # repeat outer loop over x 2 0

Alternative Scripting Languages perl exceptional text manipulation and parsing python designed for clarity rather than compactness; excellent scientific and numerical extensions php used for preprocessing dynamic web pages sed stream editor for text manipulation awk operates on fields (columns) of data Tcl/Tk ancient; for creating windows via GUI library make for building executable programs from source code Expect automates interactions with programs that expect user input 2

Thank you Slides available at: https://github.com/researchcomputing/final_tutorial (BashProg directory) 2 2