Introduction to Unix – CS 21 Lecture 13. Lecture Overview Finding files and programs which whereis find xargs Putting it all together for some complex.

Slides:



Advertisements
Similar presentations
Shell Script Assignment 1.
Advertisements

Learning Unix/Linux Bioinformatics Orientation 2008 Eric Bishop.
Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
Find Command Characteristics –Locate files descending from multiple starting points –Employs regular expressions Examples On entire system: >find / -name.
CS 497C – Introduction to UNIX Lecture 22: - The Shell Chin-Chih Chang
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Introducing the Command Line CMSC 121 Introduction to UNIX Much of the material in these slides was taken from Dan Hood’s CMSC 121 Lecture Notes.
CS Lecture 04 Outline Change your shell Sed and awk Tricks with Bash scripts Assignment 1 discussion 1CS 311 Operating SystemsLecture 04.
CS 497C – Introduction to UNIX Lecture 34: - Shell Programming Chin-Chih Chang
More Shell Programming Learning Objectives: 1. To learn the usage of environment (shell) variables in shell programming 2. To understand the handling of.
Guide To UNIX Using Linux Third Edition
Lecture 02CS311 – Operating Systems 1 1 CS311 – Lecture 02 Outline UNIX/Linux features – Redirection – pipes – Terminating a command – Running program.
Unix Shell Scripts. What are scripts ? Text files in certain format that are run by another program Examples: –Perl –Javascript –Shell scripts (we learn.
Introduction to UNIX GPS Processing and Analysis with GAMIT/GLOBK/TRACK T. Herring, R. King. M. Floyd – MIT UNAVCO, Boulder - July 8-12, 2013 Directory.
Introduction to Unix – CS 21 Lecture 5. Lecture Overview Lab Review Useful commands that will illustrate today’s lecture Streams of input and output File.
Bash Shell Scripting 10 Second Guide Common environment variables PATH - Sets the search path for any executable command. Similar to the PATH variable.
Introduction to Linux and Shell Scripting Jacob Chan.
Understanding the Basics of Computational Informatics Summer School, Hungary, Szeged Methos L. Müller.
CS 141 Labs are mandatory. Attendance will be taken in each lab. Make account on moodle. Projects will be submitted via moodle.
Using Macs and Unix Nancy Griffeth January 6, 2014 Funding for this workshop was provided by the program “Computational Modeling and Analysis of Complex.
Introduction to UNIX/Linux Exercises Dan Stanzione.
COMP1070/2002/lec4/H.Melikian COMP1070 Lecture #5  Files and directories in UNIX  Various types of files  File attributes  Notion of pathname  Commands.
Advanced File Processing
UNIX command line. In this module you will learn: What is the computer shell What is the command line interface (or Terminal) What is the filesystem tree.
Linux environment ● Graphical interface – X-window + window manager ● Text interface – terminal + shell.
1 Operating Systems Lecture 3 Shell Scripts. 2 Brief review of unix1.txt n Glob Construct (metacharacters) and other special characters F ?, *, [] F Ex.
8 Shell Programming Mauro Jaskelioff. Introduction Environment variables –How to use and assign them –Your PATH variable Introduction to shell programming.
Agenda User Profile File (.profile) –Keyword Shell Variables Linux (Unix) filters –Purpose –Commands: grep, sort, awk cut, tr, wc, spell.
Guide To UNIX Using Linux Fourth Edition
Introduction to Unix – CS 21 Lecture 9. Lecture Overview Shell description Shell choices History Aliases Topic review.
Advanced File Processing. 2 Objectives Use the pipe operator to redirect the output of one command to another command Use the grep command to search for.
Introduction to Bash Programming Ellen Zhang. Previous three classes What have we learnt so far ?
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.
Chapter Five Advanced File Processing Guide To UNIX Using Linux Fourth Edition Chapter 5 Unix (34 slides)1 CTEC 110.
Chapter Five Advanced File Processing. 2 Objectives Use the pipe operator to redirect the output of one command to another command Use the grep command.
Module 6 – Redirections, Pipes and Power Tools.. STDin 0 STDout 1 STDerr 2 Redirections.
Agenda Regular Expressions (Appendix A in Text) –Definition / Purpose –Commands that Use Regular Expressions –Using Regular Expressions –Using the Replacement.
Agenda Link of the week Use of Virtual Machine Review week one lab assignment This week’s expected outcomes Review next lab assignments Break Out Problems.
Introduction to Unix – CS 21 Lecture 12. Lecture Overview A few more bash programming tricks The here document Trapping signals in bash cut and tr sed.
Lecture 24CS311 – Operating Systems 1 1 CS311 – Lecture 24 Outline Final Exam Study Guide Note: These lecture notes are not intended replace your notes.
Chapter Five Advanced File Processing. 2 Lesson A Selecting, Manipulating, and Formatting Information.
Unix Commands PowerPoint Presentation developed for LS 560 Information Technology online class - University of Alabama by Debey Sklenar TENacious Cohort.
Introduction to Linux Instructor: Bennett M. Tanyag PART – 3 Unit 1.
Writing Scripts Hadi Otrok COEN 346.
40 Years and Still Rocking the Terminal!
CS252: Systems Programming Ninghui Li Slides by Prof. Gustavo Rodriguez-Rivera Topic 7: Unix Tools and Shell Scripts.
Executable scripts. So far We have made scripts echo hello #for example And called it hello.sh Run it as sh hello.sh This only works from current directory?
Week Two Agenda Announcements Link of the week Use of Virtual Machine Review week one lab assignment This week’s expected outcomes Next lab assignments.
Lesson 3-Touring Utilities and System Features. Overview Employing fundamental utilities. Linux terminal sessions. Managing input and output. Using special.
– Introduction to the Shell 1/21/2016 Introduction to the Shell – Session Introduction to the Shell – Session 3 · Job control · Start,
More Unix Naomi Altman. Directories Directory = folder mkdir - makes a new directory rmdir - removes an empty directory cd mydirectory - moves you into.
Sed. Class Issues vSphere Issues – root only until lab 3.
Regular Expressions Todd Kelley CST8207 – Todd Kelley1.
CS 403: Programming Languages Lecture 20 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
1 Lecture 7 Introduction to Shell Scripts COP 3353 Introduction to UNIX.
1 UNIX Operating Systems II Part 2: Shell Scripting Instructor: Stan Isaacs.
Learning Unix/Linux Based on slides from: Eric Bishop.
Lesson 5-Exploring Utilities
Chapter 11 Command-Line Master Class
The UNIX Shell Learning Objectives:
Part 1: Basic Commands/Utilities
Some Linux Commands.
The Linux Operating System
Shell Script Assignment 1.
Sarah Diesburg Operating Systems CS 3430
CS 60 Discussion Review.
Guide To UNIX Using Linux Third Edition
Linux Shell Script Programming
Introduction to Bash Programming, part 3
Presentation transcript:

Introduction to Unix – CS 21 Lecture 13

Lecture Overview Finding files and programs which whereis find xargs Putting it all together for some complex programs

What Do You Do When You Want To Locate A File? Option 1: ls Can be very time consuming Option 2: Other programs which Used to see what you are running whereis Used to see where programs are located find A general tool to find all sorts of files in the directory

which Usage: which PROGRAMNAME Tells you what executable is being run when you run a program Useful to tell when more than one executable exists (i.e. one in /bin and one in /sbin) Only searches your PATH

Example Of which

whereis Usage: whereis PROGRAMNAME Locates the source, executable, and man page for a command Searches set paths

Example Of whereis

find Locate files based on any number of factors More than just the name When it was modified What permissions it has What size it is

Running find Usage: find [path] [expression] A little different from all other programs you’ve run Instead of a letter, options are the complete word Example: Instead of –n, you use -name

Expression Options To find -name “pattern” Matches the name of a file -iname Matches the name of a file but is case-insensitive -empty Matches empty files -type d f l

Examples

More Expression Options -atime N File was last accessed N days ago -mtime N File was last changed N days ago +N, -N +N = More than N days ago -N = Less than N days ago

Examples

Combining Expression Options -o Or -a And \( \) Grouping

Action Commands -print Simply prints out the name of the file that was found Most common action -exec Executes a command -ok Executes a command, but prompts the user first

The exec Option – A Powerful But Dangerous Option -exec COMMAND \; {} gets replaced with the name of the file that was found Example: find. –name “*.txt” –exec echo {} \; Same as find. –name “*.txt” -print

Examples

When Would You Ever Do This? The –exec option allows you to perform some command on all files that match a certain criteria Example: Someone cracked into your system and you want to check all recently modified files for any changes against a backup find –mtime –2 –exec diff {}.snapshot/{}

Problem The exec command will run the command once for every file that matches A lot of overhead May take a lot longer than you’d like Solution: xargs

The xargs Command Take values from standard in and convert them into command line parameters Usage: xargs COMMAND Example: xargs grep pattern

What? File1.txt File2.txt … Program stdin xargs Program File1.txt File2.txt …

Why? When a program outputs a list that will be used as input to another program Used mainly in pipes with find Example: find. –name *.txt | xargs grep ‘Jason’ find. –name *.txt –exec grep ‘Jason’ {} \; Calls grep many, many times less than the second call and takes less time

Another xargs example Problem: You want to kill all of your processes First, list all your processes ps aux | grep login Next, select all the PIDs cut –d’ ‘ –f2 Now pass all those PIDs to kill ps aux | grep login | cut –d’ ‘ –f2 | xargs kill -9

A Simple Cleanup Script #!/bin/bash ps aux | grep login | cut –d’ ‘ –f2 | xargs kill -9 exit 0 >./exitScript.sh &

When Would You Use Bash Versus Awk? What is bash good at? Finding and manipulating files and directories What is bash bad at? Manipulating data inside files What is awk good at? Manipulating data inside files What is awk bad at? Finding and manipulating files and directories

Building A Complex Program Start small Always try to get something working before you get something working well Build up Add functionality one part at a time and test as you go

Building A Complex Program In Bash Starting small – #!/bin/bash exit 0 Slowly add functionality #!/bin/bash read input echo $input exit 0

Building Up A Complex Program – In awk Start small { print $0 } Slowly add functionality /Pattern/ { print $0 }

Hints Break the problem down into smaller components Try printing first – always print as you go Insert temporary files or variables if needed Example: If you are required to process any number of command line parameters one at a time, start by handling just one After you can handle one, try two Generalize after you have gotten the first part down

Example

Computing Problem Find all files we haven’t changed in 2 days and move them to a folder called oldStuff Should we use bash or awk? Bash shell programming would be better

Break It Down Find all files we haven’t changed in two days find ~ –mtime +2 -print Move each file to the oldStuff folder mv file ~/oldStuff/

Put It Together We need some way to connect the first part with the second part How about a variable? Store the list of file names and then go through them one by one var=`command`

Script Solution #!/bin/bash filesToMove = `find ~ -mtime +2 –print` for f in $filesToMove do mv $f ~/oldStuff/ done exit 0

Another Computing Problem Remove all files that have the phrase “Remove Me” located on the first line Which should we use, bash or awk? We are looking inside files, but we aren’t manipulating the data, so we should use bash.

Break It Down Find all files find. –name “*” -print Get the first line head -1 Look for “Remove Me” grep “Remove Me” Remove the file if “Remove Me” was there rm file

Put It Together Variables to pass information along List of all files Temporary files or variables to store results and test Results from grep

One Script Solution #!/bin/bash allFiles=`find. –name “*” –print` for f in $allFiles do head –1 $f | grep “Remove Me” >.tmpFile if [ -s.tmpFile ] ; then rm –i $f fi done rm –f.tmpFile exit 0

Another Computing Problem Tax calculator Given a receipt, calculate the tax Receipt is a file containing the name of the product and price of the product on one line Pork Tenderloin:10.85 Should we use bash or awk? awk would be better in this case

Break It Down Calculate the tax on an individual item Get the item $2 Multiply it by the tax $2 *.0775 Sum up all the taxes

Put It Together To keep a sum, we need to store the running total in some location How about a variable? totalTax = totalTax + newTax We need to initialize the tax in the beginning and print out the tax at the end

Awk Script NF == 2 { totalTax = totalTax + $2 *.0775 } BEGIN { totalTax=0 } END { print totalTax }

Problem 4 Given a file that contains inventory, print out all items that are out of stock File format: ITEM/PRICE/QUANTITY Example: Needlenose pliers/2.50/4 Should we use bash or awk? Awk is better this time since we are checking the data

Script Solution { if ($3 == 0) { print $1 } }

Next Time Quiz #2 Bash and awk programs sed Perl Programming Introduction