L04 C Shell Scripting - Part 2



Similar documents
Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

AN INTRODUCTION TO UNIX

Advanced Bash Scripting. Joshua Malone

Unix Scripts and Job Scheduling

A Crash Course on UNIX

grep, awk and sed three VERY useful command-line utilities Matt Probert, Uni of York grep = global regular expression print

Introduction to Running Hadoop on the High Performance Clusters at the Center for Computational Research

Command Line Interface User Guide for Intel Server Management Software

Microsoft Windows PowerShell v2 For Administrators

UNIX, Shell Scripting and Perl Introduction

How to get the most out of Windows 10 File Explorer

Basic C Shell. helpdesk@stat.rice.edu. 11th August 2003

CS 103 Lab Linux and Virtual Machines

Unix the Bare Minimum

This presentation explains how to monitor memory consumption of DataStage processes during run time.

Hands-On UNIX Exercise:

CS 2112 Lab: Version Control

Working with Tables. Creating Tables in PDF Forms IN THIS CHAPTER

H-ITT CRS V2 Quick Start Guide. Install the software and test the hardware

HP LoadRunner. Software Version: Ajax TruClient Tips & Tricks

by Jonathan Kohl and Paul Rogers 40 BETTER SOFTWARE APRIL

TREK HOSC PAYLOAD ETHERNET GATEWAY (HPEG) USER GUIDE

Tutorial 0A Programming on the command line

PHP Debugging. Draft: March 19, Christopher Vickery

Apple s Automator Workshop

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Windows PowerShell Essentials

Linux Shell Script To Monitor Ftp Server Connection

Lesson 1 - Creating a Project

Using SSH Secure FTP Client INFORMATION TECHNOLOGY SERVICES California State University, Los Angeles Version 2.0 Fall 2008.

Visual Studio.NET Database Projects

Command Line - Part 1

Cloud Computing. Chapter Hadoop

PuTTY/Cygwin Tutorial. By Ben Meister Written for CS 23, Winter 2007

Remote Access to Unix Machines

Appendix K Introduction to Microsoft Visual C++ 6.0

Offline Image Viewer Guide

Creating a Java application using Perfect Developer and the Java Develo...

Working with Windows Handout

Shell Scripts (1) For example: #!/bin/sh If they do not, the user's current shell will be used. Any Unix command can go in a shell script

While Loops and Animations

UTILITY INSTRUCTION MANUAL BNP-B2196 (ENG)

Running your first Linux Program

Fruit Machine. Level. Activity Checklist Follow these INSTRUCTIONS one by one. Test Your Project Click on the green flag to TEST your code

2 Advanced Session... Properties 3 Session profile... wizard. 5 Application... preferences. 3 ASCII / Binary... Transfer

File Transfer Protocols In Anzio

Grid Engine 6. Troubleshooting. BioTeam Inc.

Introduction. Chapter 1

An Introduction to the Linux Command Shell For Beginners

File Manager Pro User Guide. Version 3.0

HP-UX Essentials and Shell Programming Course Summary

Version Control with. Ben Morgan

Visualizing molecular simulations

Spectrum Technology Platform. Version 9.0. Spectrum Spatial Administration Guide

INASP: Effective Network Management Workshops

Filtering with Microsoft Outlook

Version Control with Subversion and Xcode

Chapter 1: Getting Started

Pro/E Design Animation Tutorial*

The Einstein Depot server

Computer Programming In QBasic

NovaBACKUP Storage Server User Manual NovaStor / April 2013

Creating Drawings in Pro/ENGINEER

Zenoss Resource Manager ZenUp Installation and Administration

Syntax: cd <Path> Or cd $<Custom/Standard Top Name>_TOP (In CAPS)

INFORMATION BROCHURE Certificate Course in Web Design Using PHP/MySQL

Notepad++ The COMPSCI 101 Text Editor for Windows. What is a text editor? Install Python 3

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Extreme computing lab exercises Session one

Tutorial: Using WestGrid. Drew Leske Compute Canada/WestGrid Site Lead University of Victoria

Managing Mailbox Space and Personal Folders

If you re like most project managers, you juggle several projects at the same time.

TEL2821/IS2150: INTRODUCTION TO SECURITY Lab: Operating Systems and Access Control

EXCEL PIVOT TABLE David Geffen School of Medicine, UCLA Dean s Office Oct 2002

Linux command line. An introduction to the Linux command line for genomics. Susan Fairley

Amira License Manager

CREATING AN IMAGE FROM AUTOCAD CADD NOTE 16. MENU: AutoCAD, File, Plot COMMAND: plot ICON:

BitLocker To Go User Guide

Working With Your FTP Site

How to test and debug an ASP.NET application

DocuSign for SharePoint

DiskPulse DISK CHANGE MONITOR

TS-800. Configuring SSH Client Software in UNIX and Windows Environments for Use with the SFTP Access Method in SAS 9.2, SAS 9.3, and SAS 9.

Computer Systems II. Unix system calls. fork( ) wait( ) exit( ) How To Create New Processes? Creating and Executing Processes

Outline. Unix shells Bourne-again Shell (bash) Interacting with bash Basic scripting References

Setting up the Oracle Warehouse Builder Project. Topics. Overview. Purpose

FEI Avizo License Management

Linux Overview. Local facilities. Linux commands. The vi (gvim) editor

3. License Management - Unix & Linux

McAfee SMC Installation Guide 5.7. Security Management Center

Command Line Crash Course For Unix

ICS 351: Today's plan

PharmaSUG Paper AD11

Decision Support System to MODEM communications

Introduction to Shell Programming

CLC Server Command Line Tools USER MANUAL

Penetration Testing Ninjitsu 2: Crouching Netcat, Hidden Vulnerabilities. By Ed Skoudis

Applications Development

Transcription:

Geophysical Computing L04-1 1. Control Structures: if then L04 C Shell Scripting - Part 2 Last time we worked on the basics of putting together a C Shell script. Now, it is time to add to this the control structures that actually make scripting useful. The following example shows the three primary examples of how to test conditionally. echo Enter a number between 1 and 10 @ number = $< if ($number == 6) then echo that s the lucky number! if ($number > 5 && $number < 7) then echo that s the lucky number! echo you lose. try again. if ($number > 0 && $number < 5) then echo a low pick. if ($number >= 7 && $number <= 10) then echo a high pick. if ($number == 6) then echo that s the lucky number! echo you didn t pick a number between 1 and 10! echo follow the instructions and try again... Remember though, when testing numbers in a C Shell script, it can not handle real numbers! 2. Control Structures: goto I shudder to actually write down the goto statement. It is, in my opinion, an abomination. It was relegated obsolete back in the 60 s, yet here it is, still in existence in a handful of languages. Here are a couple of quick examples on how to use it, and then I wash my hands of it! First, let s just look at the example given above, and put a goto statement in, such that if you choose a number outside of the range 1 to 10 the script will force you to re-pick a number.

Geophysical Computing L04-2 select: echo Enter a number between 1 and 10 @ number = $< if ($number > 0 && $number < 5) then echo a low pick. if ($number >= 7 && $number <= 10) then echo a high pick. if ($number == 6) then echo that s the lucky number! echo you didn t pick a number between 1 and 10! echo follow the instructions and try again... goto select The following example shows how one could test for the proper usage of a C Shell script: # # Example script requires 2 command line arguments # 1) the name of an input file, 2) the name of an output file if ($#argv < 2) goto usage set ifile = $argv[1] set ofile = $argv[2] exit 1 usage: echo Usage: myprog input_file output_file My hands are clean. 3. Control Structures: loops Once you can loop you are pretty much set. There are two main ways to loop in a C Shell: either with a while or a foreach statement. Examples of each are given below.

Geophysical Computing L04-3 Example of using a while statement: #Example of looping through a list of files. # # e.g., imagine I have a bunch of SAC files that all end with the # suffix.r # i.e., I have them all rotated to the radial component. # Now I want to do something with those files, in this example # use SAC to cut them. #make a temporary file listing all of my.r files ls *.R >! file_list # find out how many files I have @ nr = `awk END {print NR} file_list` @ n = 1 # define a looping variable # start the loop while ($n <= $nr) #grab nth file name from the list set if = `awk NR == $n {print $1} file_list` echo cutting file $if.. sac << eof r $if cuterr fillz cut 0 200 r w over q eof @ n = $n + 1 #increase n by one end # end loop # clean up temporary files rm file_list

Geophysical Computing L04-4 Example of using a foreach statement: set phase_list = (ScP PcP P) set depths = (100.0 200.0 300.0 400.0 500.0 600.0) # loop through all seismic phases and depths set above foreach phase ($phase_list) foreach depth ($depths) echo $phase $depth end end 4. Control Structures: Switch Case This is a really nice structure that is similar to an if then type of structure. Suppose I wanted to do some action based on what kind of seismic arrival I was looking at. So, if I was interested in a PKP arrival I could write some code that did tests like: if ($some_string == PKP ) then do something if ($some_string == SKS ) then do something do another something OK, a more elegant way to do this is to use the Switch Case structure: set input_phase = PKP switch ($input_phase) case PKP: echo PKP arrival case SKS: echo SKS arrival case SPdKS: echo SPdKS arrival endsw

Geophysical Computing L04-5 5. Control Structures: if then revisited Sometimes to make your scripts more robust it is useful to do some checks before you actually implement some action. For example, no sense in trying to move the file named blah, if the file blah doesn t even exist. To see how this works, create a temporary file named: example.txt and a temporary directory named: ExampleDir. So, let s do some tests on these temporary files (in the Linux system directories are really just files as well). set if = example.txt set id = ExampleDir # so we don t have to type out the # filename a bunch of times. # as above if (-e $if) then echo the file $if exists! if (-e $id) then echo $id exists! if (-f $id) then echo $id is a normal file echo $id is NOT normal. if (-d $id) then echo $id is a directory! The table below shows all of the attributes one may search for relating to files: Letter d e f o r w x z Attribute The file is a directory file. The file exists. The file is an ordinary file. The user owns the file. The user has read access to the file. The user has write access to the file. The user has execute access to the file. The file is 0 bytes long.

Geophysical Computing L04-6 6. The Dialog utility Let s wrap up our lectures on C Shell scripting with an entertaining utility. Perhaps you want to impress your advisor and make him/her think you ve already developed these mad hacking skills. Well, try asking for input using the dialog utility. I guarantee that you will impress the entire faculty in this Dept. (with the exception of me of course). As a quick demo: dialog --title ----- WARNING ----- \ --infobox This computer will explode \ unless you press a key within the next 5 seconds! 7 50; set exit_status = $? The dialog utility uses the following syntax: dialog --title {title} --backtitle {backtitle} {Box options} where Box options can be one of the following (other options also exist if you check out the man page) --yesno {text} {height} {width} --msgbox {text} {height} {width} --infobox {text} {height} {width} --inputbox {text} {height} {width} [{init}] --textbox {file} {height} {width} --menu {text} {height} {width} {menu} {height} {tag1} item1}... Here is an example of how to create a yes/no box: set ifile = blah.txt dialog --title ----- Yes/No Example ----- \ --yesno Do you want to delete file $ifile 7 60 set exit_status = $? # get the dialog utilities exit status echo switch ($exit_status) case 0: #user selected yes echo Deleting file $ifile rm $ifile

Geophysical Computing L04-7 case 1: #user selected no echo Saving file $ifile case 255: #user hit escape key echo Operation Canceled endsw As a final example of the dialog utility, let s use it to grab some text from the user. In this example we will prompt the user to type in a file name to delete: dialog -- title ----- Text Input Example ----- \ -- inputbox Enter the name of the file you want to delete \ 7 60 file \ --stdout > temp_menu.txt set exit_status = $? #get the dialog utilities exit status #get the string that the user typed in the input box set ifile = `cat temp_menu.txt` echo switch ($exit_status) endsw case 0: #A file name was entered echo Deleting file $ifile case 1: #The cancel button was pressed echo Cancel button pressed case 255: #User hit the escape key echo Escape key pressed rm temp_menu.txt #get rid of temporary files

Geophysical Computing L04-8 7. Debugging C Shell Scripts There are two quick ways in which one can debug a C Shell script. The script can either be run from the command line as in one of the following two examples: >> csh x myscript >> csh v myscript or, the top most line of the script can be written as follows: x v The x option echoes the command line after variable substitution. The v option echoes the command line before variable substitution. 8. Homework 1) Write a C Shell script that will loop through a list of files, and add a counter to the beginning of the filename. For example, if I have 10 files named: a.txt b.txt c.txt j.txt The code should move the files to be named: 01_a.txt 02_b.txt 03_c.txt 10_j.txt This kind of utility is often needed in naming files. Especially, as we will see in later lectures when automatically generating animations or movie files. 2) Write a C Shell script that will repeat a command many times. We will call this script: forever. For example, sometimes I want to see if a job I submitted to the supercomputer has started yet. To do so I would type qstat a. Well, I m anxious to see if it starts, so I will keep typing qstat a until I get confirmation that indeed the job did start. Instead I want to type forever qstat a, and what should happen is that qstat a keeps getting invoked (after a couple seconds delay) until I decide to cancel it. Your script should be able to take any Unix command as input. For example, it should work as forever ls, or forever ls la, or forever cat inputfile, etc.

Geophysical Computing L04-9 3) In the C Shell one can not do floating point operations. That is, you can not do math with real numbers. However, it is sometimes necessary to do so. A quick work around is to do the math inside a program like the basic calculater (e.g., use: bc -l). Write a shell script that will allow you to do a simple calculation on floating point numbers. Take as input a coordinate position in polar coordinates (Radius, and angle theta in degrees) and output the equivalent Cartesian coordinate position. 4) Write a C Shell script using the dialog utility to create a menu box. The menu box should provide several options of actions you want to carry out on a seismogram. For example, the menu box may have options as follows: Please choose an Action to be performed on Seismogram: 1 Flip Polarity of Seismogram 2 Low Pass Filter Seismogram 3 Make Time Picks on Seismogram 4 Discard Seismogram The script doesn t actually have to perform any actions on a seismogram file, but is aimed at getting you to write a script using the dialog utility. Output, in the form of some kind of recognition of which option was chosen should be provided in the code.