bash scripting continued; remote X windows; unix tidbits

Slides:



Advertisements
Similar presentations
Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
Advertisements

ATS Programming Short Course I INTRODUCTORY CONCEPTS Tuesday, Jan. 27 th, 2009 Essential Unix Commands.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
1 CSE 390a Lecture 6 bash scripting continued; remote X windows; unix tidbits slides created by Marty Stepp, modified by Jessica Miller
CS 497C – Introduction to UNIX Lecture 33: - Shell Programming Chin-Chih Chang
1 CSE 303 Lecture 6 more Unix commands; bash scripting continued read Linux Pocket Guide pp , 82-88, slides created by Marty Stepp
Shell Programming 1. Understanding Unix shell programming language: A. It has features of high-level languages. B. Convenient to do the programming. C.
Bash Shell Scripting 10 Second Guide Common environment variables PATH - Sets the search path for any executable command. Similar to the PATH variable.
Shell Programming. Shell Scripts (1) u Basically, a shell script is a text file with Unix commands in it. u Shell scripts usually begin with a #! and.
Lab 8 Shell Script Reference:
Unix/Linux basics 0011 Operating systems lab Gergely Windisch room 4.12
1 Operating Systems Lecture 3 Shell Scripts. 2 Shell Programming 1.Shell scripts must be marked as executable: chmod a+x myScript 2. Use # to start a.
1 Operating Systems Lecture 3 Shell Scripts. 2 Brief review of unix1.txt n Glob Construct (metacharacters) and other special characters F ?, *, [] F Ex.
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.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
Shell Programming. Creating Shell Scripts: Some Basic Principles A script name is arbitrary. Choose names that make it easy to quickly identify file function.
1 CSE 390a Lecture 6 bash scripting continued; remote X windows; unix tidbits slides created by Marty Stepp, modified by Jessica Miller and Ruth Anderson.
1 CSE 303 Lecture 5 bash continued: users/groups; permissions; intro to scripting read Linux Pocket Guide pp slides created by Marty Stepp
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
1 CSE 390a Lecture 6 bash scripting continued; remote X windows; unix tidbits slides created by Marty Stepp, modified by Jessica Miller and Ruth Anderson.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
Shell Script2 Reference: Linux Shell Scripting Tutorial v1.05r3 A Beginner's handbook
Agenda Positional Parameters / Continued... Command Substitution Bourne Shell / Bash Shell / Korn Shell Mathematical Expressions Bourne Shell / Bash Shell.
Lab 8 Shell Script Reference: Linux Shell Scripting Tutorial v1.05r3 A Beginner's handbook
Shell script – part 2 CS 302. Special shell variable $0.. $9  Positional parameters or command line arguments  For example, a script myscript take 2.
Assigning Values 1. $ set One Two Three [Enter] $echo $1 $2 $3 [Enter] 2. $set `date` [Enter] $echo $1 $2 $3 [Enter] 3. $echo $1 $2 $3 $4 $5 $6 [Enter]
1 UNIX Operating Systems II Part 2: Shell Scripting Instructor: Stan Isaacs.
1 CSE 391 Lecture 6 bash scripting continued; remote X windows; unix tidbits slides created by Marty Stepp, modified by Jessica Miller and Ruth Anderson.
1 Lecture 8 Shell Programming – Control Constructs COP 3353 Introduction to UNIX.
bash scripting continued; remote X windows; unix tidbits
Persistent shell settings; users/groups; permissions
Department of Computer Engineering
CSC 352– Unix Programming, Spring 2016, Final Exam Guide
Agenda Bash Shell Scripting – Part II Logic statements Loop statements
bash scripting continued; remote X windows; unix tidbits
Lecture 9 Shell Programming – Command substitution
Persistent shell settings; users/groups; permissions
Intro to shell scripting
bash scripting continued; remote X windows; unix tidbits
Persistent shell settings; users/groups; permissions
CSE 390a Lecture 6 bash scripting continued; remote X windows; unix tidbits slides created by Marty Stepp, modified by Josh Goodwin
LING 408/508: Computational Techniques for Linguists
bash scripting continued; remote X windows; unix tidbits
More Selections BIS1523 – Lecture 9.
bash scripting continued; remote X windows; unix tidbits
Command Substitution Command substitution is the mechanism by which the shell performs a given set of commands and then substitutes their output in the.
Persistent shell settings; users/groups; permissions
bash scripting continued; remote X windows; unix tidbits
bash scripting continued; remote X windows; unix tidbits
CSE 303 Concepts and Tools for Software Development
Persistent shell settings; users/groups; permissions
Intro to shell scripting
bash scripting continued; remote X windows; unix tidbits
Presented by, Mr. Satish Pise
bash scripting continued; remote X windows; unix tidbits
bash scripting continued; remote X windows; unix tidbits
bash scripting continued; remote X windows; unix tidbits
bash scripting continued; remote X windows; unix tidbits
Intro to shell scripting
Intro to shell scripting
bash scripting continued; remote X windows; unix tidbits
bash scripting continued; remote X windows; unix tidbits
Intro to shell scripting
Introduction to Bash Programming, part 3
bash scripting continued; remote X windows; unix tidbits
Bash Scripting CS 580U - Fall 2018.
Intro to shell scripting
Review.
Persistent shell settings; users/groups; permissions
Persistent shell settings; users/groups; permissions
Presentation transcript:

bash scripting continued; remote X windows; unix tidbits CSE 391 Lecture 6 bash scripting continued; remote X windows; unix tidbits slides created by Marty Stepp, modified by Jessica Miller and Ruth Anderson http://www.cs.washington.edu/391/

Lecture summary more shell scripting various new Unix/Linux commands if/else while/until select/case advanced: arrays and functions various new Unix/Linux commands newlines in Unix vs Windows Remote X windows file archiving and compression

Exit Status Every Linux command returns an integer code when it finishes, called its “exit status” 0 usually* denotes success, or an OK exit status Anything other than 0 (1 to 255) usually denotes an error You can return an exit status explicitly using the exit statement You can check the status of the last command executed in the variable $? $ cat someFileThatDoesNotExist.txt $ echo $? 1 # “Failure” $ ls 0 # “Success” * One example exception: diff returns “0” for no differences, “1” if differences found, “2” for an error such as invalid filename argument

if/else if [ condition ]; then # basic if commands fi if [ condition ]; then # if / else if / else commands1 elif [ condition ]; then commands2 else commands3 The [ ] syntax is actually shorthand for a shell command called “test” (Try: “man test”) there MUST be spaces as shown: if space [ space condition space ] include the semi-colon after ] (or put “then” on the next line)

The test command $ test 10 –lt 5 $ echo $? 1 # “False”, “Failure” $ test 10 –gt 5 0 # “True”, “Success” Another syntax for the test command: Don’t forget the space after [ and before ] $ [ 10 –lt 5 ] $ [ 10 –gt 5 ]

<, <=, ==, >, >=, != test operators comparison operator description =, !=, \<, \> compares two string variables -z, -n tests if a string is empty (zero-length) or not empty (nonzero-length) -lt, -le, -eq, -gt, -ge, -ne compares numbers; equivalent to Java's <, <=, ==, >, >=, != -e, -f, -d tests whether a given file or directory exists -r, -w, -x tests whether a file exists and is readable/writable/executable if [ $USER = “husky14" ]; then echo ‘Woof! Go Huskies!’ fi LOGINS=$(w -h | wc -l) if [ $LOGINS -gt 10 ]; then echo ‘attu is very busy right now!’ *Note: man test will show other operators.

compound comparison operators More if testing # alert user if running >= 10 processes when # attu is busy (>= 5 users logged in) LOGINS=$(w -h | wc -l) PROCESSES=$(ps -u $USER | wc -l) if [ $LOGINS -ge 5 -a $PROCESSES -gt 10 ]; then echo "Quit hogging the server!" fi compound comparison operators description if [ expr1 -a expr2 ]; then ... if [ expr1 ] && [ expr2 ]; then ... and if [ expr1 -o expr2 ]; then ... if [ expr1 ] || [ expr2 ]; then ... or if [ ! expr ]; then ... not -a does NOT short circuit As seen previously, && short circuits || short circuits

safecopy Exercise Write a script called safecopy that will mimic the behavior of cp –i where from is a filename and to is a filename: $ cp –i from.txt to.txt Do you want to overwrite to.txt? (yes/no) $ ./safecopy.sh from.txt to.txt

safecopy Exercise Solution #!/bin/bash FROM=$1 TO=$2 if [ -e $TO ]; then read -p "Do you want to overwrite $TO?" ANSWER if [ $ANSWER = "yes" ]; then cp $FROM $TO fi else HIDE

BMI Exercise Write a program that computes the user's body mass index (BMI) to the nearest integer, as well as the user's weight class: $ ./bmi.sh Usage: ./bmi.sh weight height $ ./bmi.sh 112 72 Your Body Mass Index (BMI) is 15 Here is a sandwich; please eat. $ ./bmi.sh 208 67 Your Body Mass Index (BMI) is 32 There is more of you to love. BMI Weight class  18 underweight 18 - 24 normal 25 - 29 overweight  30 obese

BMI Exercise solution #!/bin/bash # Body Mass Index (BMI) calculator if [ $# -lt 2 ]; then echo "Usage: $0 weight height" exit 1 # 1 indicates failure, 0 for success fi let H2=“$2 * $2” let BMI="703 * $1 / $H2" echo "Your Body Mass Index (BMI) is $BMI" if [ $BMI -le 18 ]; then echo "Here is a sandwich; please eat." elif [ $BMI -le 24 ]; then echo "You're in normal weight range." elif [ $BMI -le 29 ]; then echo "You could stand to lose a few." else echo "There is more of you to love." HIDE

Common errors [: -eq: unary operator expected [: too many arguments you used an undefined variable in an if test [: too many arguments you tried to use a variable with a large, complex value (such as multi-line output from a program) as though it were a simple int or string let: syntax error: operand expected (error token is " ") you used an undefined variable in a let mathematical expression

while and until loops while [ condition ]; do # go while condition is true commands done until [ condition ]; do # go while condition is false

While exercise Prompt the user for what they would like to do. While their answer is “open the pod bay doors” tell them that you cannot do that and prompt for another action.

While Exercise solution #!/bin/bash # What would you like to do? read -p "What would you like me to do? " ACTION echo "You said: $ACTION" while [ "$ACTION" = "open the pod bay doors" ]; do echo "I'm sorry Dave, I'm afraid I can't do that." done echo "Bye" HIDE The quotes around “$ACTION” are important here, try removing them and see what happens.

select and case Bash Select statement: PS3=prompt # Special variable* for the select prompt select choice in choices; do commands break # Break, otherwise endless loop done Bash Case statement: case EXPRESSION in  CASE1) COMMAND-LIST;;  CASE2) COMMAND-LIST;; ...  CASEN) COMMAND-LIST;; esac *see lecture 5

Select Example PS3="What is your favorite food? " # Goes with the select stmt echo "Welcome to the select example!" echo "It prints out a list of choices" echo "but does nothing interesting with the answer." select CHOICE in "pizza" "sushi" "oatmeal" "broccoli"; do echo "You picked $CHOICE" break done echo “For the select statement, you pick a number as your choice."

Case Example echo "Welcome to the case example!" echo "Without a select statement, you must get the spelling/case exact." read -p "What format do you prefer? (tape/cd/mp3/lp) " FORMAT echo "You said $FORMAT" case "$FORMAT" in "tape") echo "no random access!";; "cd") echo "old school";; "mp3") echo "how modern";; "lp") echo "total retro";; esac

select/case Exercise Have the user select their favorite kind of music, and output a message based on their choice

select/case Exercise Solution PS3="What is your favorite kind of music? " select CHOICE in "rock" "pop" "dance" "reggae"; do case "$CHOICE" in "rock") echo "Rock on, dude.";; "pop") echo "Top 100 is called that for a reason.";; "dance") echo "Let's lay down the Persian!";; "reggae") echo "Takin' it easy...";; * ) echo "come on...you gotta like something!";; esac break done HIDE

Arrays name=(element1 element2 ... elementN) name[index]=value # set an element $name # get first element ${name[index]} # get an element ${name[*]} # elements sep.by spaces ${#name[*]} # array's length arrays don't have a fixed length; they can grow as necessary if you go out of bounds, shell will silently give you an empty string you don't need to use arrays in assignments in this course Indexing starts counting at zero.

Functions function name() { # declaration commands # ()’s are optional } name # call functions are called simply by writing their name (no parens) parameters can be passed and accessed as $1, $2, etc. (icky) you don't need to use functions in assignments in this course The function definition must precede the first call to it. Can do recursion – but please don’t!

Other useful tidbits

Newlines in Windows/Unix Early printers had two different command characters: Carriage return (\r) – move the print head back to the left margin Line feed (\n) – move the paper to the next line Both occurred when you wanted a “newline” As time went on, various combos were used to signify a “newline” Windows typically uses the (\r\n) version MacOS uses (\r) Unix uses (\n) Can cause problems when displaying text files created on one system on another system Most modern text editors recognize both and do the right thing Can convert if needed: dos2unix and unix2dos commands

ssh -X attu.cs.washington.edu Remote X display Normally, you can’t run graphical programs on remote servers (e.g. attu) however, if you connect your SSH with the -X parameter, you can! the X-Windows protocol is capable of displaying programs remotely ssh -X attu.cs.washington.edu Other options (-Y for “Trusted” mode, -C for compressed, see online) Then try: xeyes, xterm, xclock

Tar slides – from lecture 4

tar files To create a single file from multiple files: description tar create or extract .tar archives (combines multiple files into one .tar file) Originally used to create “tape archive” files Combines multiple files into a single .tar file You probably always want to use –f option and IT SHOULD COME LAST To create a single file from multiple files: $ tar -cf filename.tar stuff_to_archive -c creates an archive -f read to/from a file stuff_to_archive - can be a list of filenames or a directory To extract files from an archive: $ tar -xf filename.tar -x extracts files from an archive

Compressed files To compress a file: $ gzip filename produces: filename.gz To uncompress a file: $ gunzip filename.gz produces: filename Similar for zip, bzip2. See man pages for more details. command description zip, unzip create or extract .zip compressed archives gzip, gunzip GNU free compression programs (single-file) bzip2, bunzip2 slower, optimized compression program (single-file)

.tar.gz archives Many Linux programs are distributed as .tar.gz archives (sometimes called .tgz) You could unpack this in two steps: gzip foo.tar.gz produces: foo.tar tar –xf foo.tar extracts individual files You can also use the tar command to create/extract compressed archive files all in one step: $ tar -xzf filename.tar.gz -x extracts files from an archive -z filter the archive through gzip (compress/uncompress it) -f read to/from a file Handy tip: You can use the “file” command to see what type a file is, just changing the file extension on a file does not change its type.

tar examples You can combine options (-v, -z, etc.) various ways: Create a single .tar archive file from multiple files (without compression): $ tar -cvf filename.tar stuff_to_archive -c creates an archive file called filename.tar -v verbosely list the files processed -f read to/from a file (as opposed to a tape archive) stuff_to_archive - can be filenames or a directory Add –z option and use filename.tar.gz to use compression: $ tar -cvzf filename.tar.gz stuff_to_archive

tar https://xkcd.com/1168/