CS 25200: Systems Programming. Lecture 10: Shell Scripting in Bash
|
|
- Aleesha Sherman
- 6 years ago
- Views:
Transcription
1 CS 25200: Systems Programming Lecture 10: Shell Scripting in Bash Dr. Jef Turkstra 2018 Dr. Jeffrey A. Turkstra 1
2 Lecture 10 Getting started with Bash Data types Reading and writing Control loops Decision making Indexed arrays Basic regular expressions 2018 Dr. Jeffrey A. Turkstra 2
3 Shells There are many diferent shells available for *NIX-based computers. Some of them even run under that other OS. A shell is basically a command interpreter. It provides an interface between the user and the computer (operating system). Shells may be graphical (explorer.exe, for instance) or text-based - often times called a CLI or command line interface 2018 Dr. Jeffrey A. Turkstra 3
4 Shells cont When we write a shell script, the first line of the file tells the operating system which shell to use. Some common *NIX shells include: #! /bin/sh Bourne shell #! /bin/csh C-Shell #! /bin/ksh KornShell (more powerful) #! /bin/bash Bourne-Again SHell 2018 Dr. Jeffrey A. Turkstra 4
5 Bash "Bash is the GNU Project's shell. Bash is the Bourne Again SHell. Bash is an sh-compatible shell that incorporates useful features from the Korn shell (ksh) and C shell (csh). It is intended to conform to the IEEE POSIX P1003.2/ISO Shell and Tools standard. It ofers functional improvements over sh for both programming and interactive use. In addition, most sh scripts can be run by Bash without modification." Dr. Jeffrey A. Turkstra 5
6 Diving in - variables Declaration and definition: NAME="whatever" with no spaces between or after the "=" Accessed as $NAME,, or better, ${NAME} Examples: MagicVariable1=7 MagicVariable2="Hello!" MagicVariable3= MagicVariable4=${MagicVariable1} 2018 Dr. Jeffrey A. Turkstra 6
7 Special Bash "variables" Bash has some built-in variables that allow us to get at some important information $# Number of command line arguments $* Command line arguments $0 The name of the shell script $$ Current process ID number $? Return value from last executed command $1 to $N Command line parameters (as separated by whitespace) 2018 Dr. Jeffrey A. Turkstra 7
8 echo command echo <options> Arguments Data is not formatted Writes its arguments, separated by blanks (spaces) and ending with a newline, to standard output. Whitespace can be protected with double or single quotes as needed. Example: $ echo Hello, World! Hello, World! $ 2018 Dr. Jeffrey A. Turkstra 8
9 Common echo options See man page for more detail. -n do not add a newline at the end -e turn on the special meaning of the backslash \ character -E turn of backslash (default) 2018 Dr. Jeffrey A. Turkstra 9
10 Examples echo -n "Hello" echo ", World!" echo "-n hmm" echo ":-)\n:-(" echo -e ":-)\n:-(" Results in the following output: Hello, World! -n hmm :-)\n:-( :-) :-( 2018 Dr. Jeffrey A. Turkstra 10
11 printf command - formatted output Almost like in C: printf "format" list of variables Format string is like that found in C The list of variables should be separated by spaces. Example: A=3.45 S="Big Deal" printf "A: %5.2f, S: %s\n" $A "$S" 2018 Dr. Jeffrey A. Turkstra 11
12 More Bash variables Untyped variables can be used to hold string and integer values Output: #! /bin/bash Output: A="Big Deal" Big Deal echo $A 3 A=3 2.3 echo $A A=2.3 echo $A exit Dr. Jeffrey A. Turkstra 12
13 Typed variables Integers typeset -i variable_name Integers Cannot be used to store strings 2018 Dr. Jeffrey A. Turkstra 13
14 Example #! /bin/bash typeset -i A A=3 echo "A: $A" A="Oh Well" echo "A: $A" A=2.4 echo "A: $A" exit 0 Results in the following output: A: 3 X1: line 5: Oh Well: syntax error in expression (error token is Well ) A: 3 X1: line 7: 2.4: syntax error: invalid arithmetic operator (error token is.4 ) A: Dr. Jeffrey A. Turkstra 14
15 Floating point variables Bash does not support foating point values or math. :-( 2018 Dr. Jeffrey A. Turkstra 15
16 Constants We can create read only variables too typeset -r Name="Ffej" typeset -r K=8 Or how about a read only integer typeset -ri K= Dr. Jeffrey A. Turkstra 16
17 Example #! /bin/bash typeset -r Name="Ffej Artskrut" echo $Name Name="Big Deal" echo $Name exit 0 Results in the following: $ C Ffej Artskrut./C: line 4: Name: readonly variable Ffej Artskrut 2018 Dr. Jeffrey A. Turkstra 17
18 for loops Two diferent syntaxes in Bash for variable in list do commands done where list is a set of strings separated by whitespace for (( initial_expression; loop_condition; loop_expression )) do commands done do must be on the 2 nd line in both cases! 2018 Dr. Jeffrey A. Turkstra 18
19 Examples for I in do echo -n ${I} done for (( I = 1; I < 6; I++ )) do echo -n ${I} done Both result in the same output: Dr. Jeffrey A. Turkstra 19
20 Examples cont #! /bin/bash ls *.c > temp:$$ touch temp:$$ for File in $(cat temp:$$) do lp -dsomeprinter ${File} done rm -f temp:$$ exit Dr. Jeffrey A. Turkstra 20
21 while loop Note that a command is considered "true"" as long as its exit status is zero.. This is at times backwards from what you might be used to. while <command exit status is true (0)> do <whatever commands you need to do the job> done 2018 Dr. Jeffrey A. Turkstra 21
22 Example #! /bin/bash typeset -i I=0 while (( I < 10 )) do echo -n " ${I}" (( I = I + 1 )) done echo exit 0 Outputs: Dr. Jeffrey A. Turkstra 22
23 read command read can be used to obtain user input. Eg, echo -n "Feed me data: " read DataVar echo "You fed me ${DataVar}!" It may also be used to read from other streams such as a fle. Everyone always forgets that the name of the file goes at the end of the while loop 2018 Dr. Jeffrey A. Turkstra 23
24 reading from a fle #! /bin/bash cat InFile echo while read A B C do echo "A: ${A} " \ "B: ${B} " \ "C: ${C} " done < InFile exit Dr. Jeffrey A. Turkstra 24
25 Output This is the output generated from the cat command, which simply displays a file's contents to stdout: This is Neat! CS 252 is Great! Ffej is the best Big Deal 1234 This is the output generated by the echo statement inside of the while loop: A: This B: is C: Neat! A: CS B: 252 C: is Great! A: Ffej B: is C: the best. A: 1 B: 2 C: A: Big B: Deal C: A: 1234 B: C: 2018 Dr. Jeffrey A. Turkstra 25
26 Bash math Bash only has integer math. Use let or (( )) to isolate mathematical statements Basic math operators include: addition (+),( subtraction (-),( multiplication (*),( division (/), and modulus (%)( 2018 Dr. Jeffrey A. Turkstra 26
27 Integer math example #! /bin/bash typeset -i a=11 typeset -i b=3 typeset -i x (( x = a + b )) echo "(( x = $a + $b )) x = $x" (( x = a - b )) echo "(( x = $a - $b )) x = $x" (( x = a * b )) echo "(( x = $a * $b )) x = $x" (( x = a / b )) echo "(( x = $a / $b )) x = $x" (( x = a % b )) echo "(( x = $a % $b )) x = $x" exit Dr. Jeffrey A. Turkstra 27
28 Output (( x = )) x = 14 (( x = 11-3 )) x = 8 (( x = 11 * 3 )) x = 33 (( x = 11 / 3 )) x = 3 (( x = 11 % 3 )) x = Dr. Jeffrey A. Turkstra 28
29 Branching if command true then commands else commands fi Note: the command is "true" if it returns 0 - neat! 2018 Dr. Jeffrey A. Turkstra 29
30 Nested if statements As one might expect, it is possible to nest branches in ksh if (( A < B )) then echo "A < B" else if (( A == B )) then echo "A = B" else echo "A > B" fi fi 2018 Dr. Jeffrey A. Turkstra 30
31 elif statement Equivalent to "else if" in C if (( A < B )) then echo "A < B" elif (( A == B )) then echo "A = B" else echo "A > B" fi 2018 Dr. Jeffrey A. Turkstra 31
32 Testing Tests of any sort should be surrounded by double brackets with spaces: [[ space whatever space ]] Example if [[ -r MyFile ]] then echo MyFile is readable! fi Tests include logical comparisons, string comparisons, and file permission tests 2018 Dr. Jeffrey A. Turkstra 32
33 File testing -a file exists -d is a directory -f is an ordinary file -r is readable -s has non-zero length -w is writable -x is executable and lots more! reverse the test 2018 Dr. Jeffrey A. Turkstra 33
34 Arithmetic comparison Comparisons between numbers should always be surrounded by double parentheses: (( whatever )) For example: if (( 7 <= 5 )) then echo "The world is at an end!" fi Arithmetic comparisons include: == equal >= greater than or equal > greater than <= less than or equal < less than!= not equal 2018 Dr. Jeffrey A. Turkstra 34
35 String tests Equality, if [[ string1 = string2orpattern ]] if [[ string1 == string2orpattern ]] if [[ string1!= string2orpattern ]] Lexicographical ordering, if [[ string1 < string2 ]] if [[ string1 > string2 ]] Emptiness, if [[ -n string1 ]] # string is not NULL if [[ -z string1 ]] # string is NULL 2018 Dr. Jeffrey A. Turkstra 35
36 Example #! /bin/bash # if (( $#!= 1 )); then echo "Usage: $0 <filename>" exit 1 fi File="$1" if [[! -f "${File}" ]]; then echo "File: ${File} is not an ordinary file" else echo "File: ${File} is an ordinary file" fi exit Dr. Jeffrey A. Turkstra 36
37 Output $ File_Check Usage: File_Check <filename> $ File_Check x File x is not an ordinary file $ File_Check File_Check File File_Check is an ordinary file 2018 Dr. Jeffrey A. Turkstra 37
38 Arrays in Bash Unlike C, bash supports sparse arrays ArrVar[5]=8 ArrVar[15]=12 ArrVar[19]=7 If the indices aren't consecutive, how do we know the array's size? How do we know the indices for all values? 2018 Dr. Jeffrey A. Turkstra 38
39 Special operators # and! You can obtain a list (a string of whitespace-separated values) of every element in an array: echo ${ArrVar[*]} echo ${ArrVar[@]} The size of an array can be found by using the # operator: ${#ArrVar[*]} or ${#ArrVar[@]} The array subscripts can be found by using the! operator: ${!ArrVar[*]} or ${!ArrVar[@]} 2018 Dr. Jeffrey A. Turkstra 39
40 Indexed array example #! /bin/bash A[5]=34 A[1]=3 A[2]=56 A[100]=89 echo "Size of array: ${#A[*]}" echo "Array indices: ${!A[*]}" for I in ${!A[*]} do echo "A[${I}]=${A[I]}" done exit Dr. Jeffrey A. Turkstra 40
41 Indexed array output Size of array: 4 Array indices: A[1]=3 A[2]=56 A[5]=34 A[100]= Dr. Jeffrey A. Turkstra 41
42 Read array example #! /bin/bash echo "Data_File:" cat Data_File # Remember, cat just dumps the file's echo # contents to stdout echo "Formatted output:" while read -a Data # Split on whitespace do # (spaces and tabs) for (( I = 0; I < ${#Data[*]}; I++ )) do printf "%6.2f" ${Data[I]} done echo done < Data_File exit Dr. Jeffrey A. Turkstra 42
43 Output Data_File: Formatted output Dr. Jeffrey A. Turkstra 43
44 More on loops Similar to C, bash has continue n Used to stop the execution of the innermost n loops and then continue with the next loop. The default is n = 1. break n Used to end the execution of the innermost n loops. Default is n = Dr. Jeffrey A. Turkstra 44
45 Examples #! /bin/bash for (( I = 0; I <= 4; I++ )); do if (( I == 1 )); then continue fi echo -n " ${I}" done echo exit 0 Results in the following output: Dr. Jeffrey A. Turkstra 45
46 Examples cont #! /bin/bash I=0 while (( I <= 4 )); do if (( I == 1 )); then break fi echo -n " ${I}" (( I++ )) done echo exit 0 Results in the following: Dr. Jeffrey A. Turkstra 46
47 What about arguments? What if we want to loop through the command line arguments? Even if we know how many there are, we still can't use a loop construct #! /bin/bash for (( I = 0; I < $#; I++ )); do echo $what??? done 2018 Dr. Jeffrey A. Turkstra 47
48 shift n Used to left shift the parameters on the command line n places Default is n = 1 $0 is never changed Often used when an unknown number of parameters are passed, or for looping through a large number of parameters Dr. Jeffrey A. Turkstra 48
49 Example #! /bin/bash echo '$0 -- ' $0 echo '$# -- ' $# X=0 while (( $#!= 0 )); do (( X = X + 1 )) echo "\"\$${X}\" was $1" shift done exit 0 Sample run $ parameters q "1 2 3" xyz $0 -- parameters $# -- 3 "$1" was q "$2" was "$3" was xyz 2018 Dr. Jeffrey A. Turkstra 49
50 Trouble with quotes There are various kinds of quotes, and each one can mean something diferent in ksh. ' The single forward quote character " The double quote character ` The back quote character \ The backslash character (sometimes used to escape quotes) 2018 Dr. Jeffrey A. Turkstra 50
51 The single forward quote ' Must appear in pairs Protects all characters between the pair of quotes Ignores all special characters Protects whitespace 2018 Dr. Jeffrey A. Turkstra 51
52 Single quote examples Path='/b/cs252' echo The path for cs252 is $Path Displays: The path for cs252 is /b/cs252 echo 'The path for cs252 is $Path' Displays: The path for cs252 is $Path echo 'The book costs $2.00' Displays: The book cost $ Dr. Jeffrey A. Turkstra 52
53 Wildcard * exception #! /bin/bash ls echo * echo '*' yuk='*' echo $yuk echo '$yuk' exit 0 Produces the following output: Chap-1 TESTS TV memo x y Chap-1 TESTS TV memo x y * Chap-1 TESTS TV memo x y $yuk 2018 Dr. Jeffrey A. Turkstra 53
54 The double quote " Must come in pairs Protects whitespace Does not ignore Dollar signs - $ Back quotes - ` Backslashes - \ 2018 Dr. Jeffrey A. Turkstra 54
55 Double quote example Path="/b/bee264" echo "The path for ee264 is $Path" Yields: The path for ee264 is /b/ee264 echo "The book cost \$2.00" Yields: The book cost $ Dr. Jeffrey A. Turkstra 55
56 Wildcard * exception #! /bin/bash ls echo * echo "*" yuk="*" echo $yuk echo "$yuk" exit 0 Produces the following output: Chap-1 TESTS TV memo x y Chap-1 TESTS TV memo x y * Chap-1 TESTS TV memo x y * 2018 Dr. Jeffrey A. Turkstra 56
57 The back quote ` Used to issue a UNIX command and obtain its output... #! /bin/bash echo "Current directory is `pwd`" DIR=`pwd` echo "Directory is ${DIR}" exit 0 Outputs: Current directory is /a/turkstra/252 Directory is /a/turkstra/ Dr. Jeffrey A. Turkstra 57
58 $(command) "Better" way to issue a UNIX command and obtain its output Makes your code easier to read, easier to debug #! /bin/bash echo "Current working directory is $(pwd)" DIR=$(pwd) echo "Directory is ${DIR}" exit 0 Results in Current directory is /a/turkstra/252 Directory is /a/turkstra/ Dr. Jeffrey A. Turkstra 58
59 The backslash \ Used to remove any special meaning that a symbol may have. \$1.00 "escapes" the $ character, treating it as a literal $ instead of $1 (the first argument passed to the script) Used to add special meaning to symbols. \n for newline, for example. If it is the last symbol on a line, it will act as a continuation indicator Dr. Jeffrey A. Turkstra 59
60 Backslash example #! /bin/bash echo "This item costs \$2.00" echo -n "This is line 1, " echo "this is the rest of the line" echo "This is" \ "\"$(whoami)\"" # \" used to print " exit 0 Outputs This item costs $2.00 This is line 1, this is the rest of the line This is "turkstra" 2018 Dr. Jeffrey A. Turkstra 60
61 Whitespace protection #! /bin/bash DATA=$(cat $0) echo ${DATA} echo echo "${DATA}" exit 0 Displays: #! /bin/ksh DATA=$(cat $0) print ${DATA} print print "${DATA}" exit 0 #! /bin/ksh DATA=$(cat $0) print ${DATA} print print "${DATA}" exit Dr. Jeffrey A. Turkstra 61
62 grep command Used to search files for lines of information. Many, many fags - see the man page. grep -flags regular_expression filename Useful fags -x Exact match of line -i Ignore upper/lower case -c Only count the number of lines which match -n Add relative line numbers -b Add block numbers -v Output all lines which do not match 2018 Dr. Jeffrey A. Turkstra 62
63 Simple regular expressions Regular expressions express patterns. They are used to find and/or extract pieces of information from a string.. Matches any character ^ Start of line $ End of line \ Escape character [list] Matches any character in the list [^list] Matches any character not in the list * Match zero or more occurrences of the previous regular expression \{min,max\} Matches at least min and at most max occurrences of the previous regular expression 2018 Dr. Jeffrey A. Turkstra 63
64 Examples grep "^string$" file_name collects all lines which contain only string grep " " file_name collects all lines which have any three characters surrounded by spaces grep " [0-9]\{1,3\} " file_name collects all lines containing a sequence of one to three digits surrounded by spaces grep "^x*[abc]" file_name collects all lines which start with zero or more x's followed by a single a, b, or c 2018 Dr. Jeffrey A. Turkstra 64
65 More examples Let's pretend we have a file named data abd asdf And this script #! /bin/bash # begins with 1 or 2 grep "^[0-9]\{1,2\} " data # digits followed by exit 0 # a space We should get this output abd 2018 Dr. Jeffrey A. Turkstra 65
66 -v option, inverting the match Let's pretend we have a file named data abd asdf And this script #! /bin/bash grep -v "^[0-9]\{1,2\} " data exit 0 We should get this output asdf 2018 Dr. Jeffrey A. Turkstra 66
67 -c option, counting the matches Let's pretend we have a file named data abd asdf And this script #! /bin/bash grep -c "^[0-9]\{1,2\} " data exit 0 We should get this output Dr. Jeffrey A. Turkstra 67
68 -n option, adding line numbers Let's pretend we have a file named data abd asdf And this script #! /bin/bash grep -n "^[0-9]\{1,2\} " data exit 0 We should get this output 2: :3 abd 2018 Dr. Jeffrey A. Turkstra 68
69 Using grep inside a script #! /bin/bash if (( $#!= 1 )); then echo "Usage: $0 <user_id>" exit 1 fi USER="$1" if grep "${USER}" Id_File > /dev/null then echo "Bad way: ${USER} in file" else echo "Bad way: ${USER} not in file" fi if grep "^${USER}$" Id_File > /dev/null then echo "Good way: ${USER} in file" else echo "Good way: ${USER} not in file" fi exit Dr. Jeffrey A. Turkstra 69
70 Output $ cat Id_File $ Check sam Usage: Check <user_id> maryann $ Check jeff john Bad way: jeff in file jeff Good way: jeff in file jeffrey $ Check son bill Bad way: son in file william Good way: son not in file peterson 2018 Dr. Jeffrey A. Turkstra 70
71 Questions? 2018 Dr. Jeffrey A. Turkstra 71
CS 25200: Systems Programming. Lecture 11: *nix Commands and Shell Internals
CS 25200: Systems Programming Lecture 11: *nix Commands and Shell Internals Dr. Jef Turkstra 2018 Dr. Jeffrey A. Turkstra 1 Lecture 11 Shell commands Basic shell internals 2018 Dr. Jeffrey A. Turkstra
More informationCSCI 211 UNIX Lab. Shell Programming. Dr. Jiang Li. Jiang Li, Ph.D. Department of Computer Science
CSCI 211 UNIX Lab Shell Programming Dr. Jiang Li Why Shell Scripting Saves a lot of typing A shell script can run many commands at once A shell script can repeatedly run commands Help avoid mistakes Once
More informationTable 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
Summer 2010 Department of Computer Science and Engineering York University Toronto June 29, 2010 1 / 36 Table of contents 1 2 3 4 2 / 36 Our goal Our goal is to see how we can use Unix as a tool for developing
More informationA shell can be used in one of two ways:
Shell Scripting 1 A shell can be used in one of two ways: A command interpreter, used interactively A programming language, to write shell scripts (your own custom commands) 2 If we have a set of commands
More informationVi & Shell Scripting
Vi & Shell Scripting Comp-206 : Introduction to Week 3 Joseph Vybihal Computer Science McGill University Announcements Sina Meraji's office hours Trottier 3rd floor open area Tuesday 1:30 2:30 PM Thursday
More informationLinux shell scripting Getting started *
Linux shell scripting Getting started * David Morgan *based on chapter by the same name in Classic Shell Scripting by Robbins and Beebe What s s a script? text file containing commands executed as a unit
More information22-Sep CSCI 2132 Software Development Lecture 8: Shells, Processes, and Job Control. Faculty of Computer Science, Dalhousie University
Lecture 8 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 8: Shells, Processes, and Job Control 22-Sep-2017 Location: Goldberg CS 127 Time: 14:35 15:25 Instructor:
More informationUNIX shell scripting
UNIX shell scripting EECS 2031 Summer 2014 Przemyslaw Pawluk June 17, 2014 What we will discuss today Introduction Control Structures User Input Homework Table of Contents Introduction Control Structures
More informationBash scripting Tutorial. Hello World Bash Shell Script. Super User Programming & Scripting 22 March 2013
Bash scripting Tutorial Super User Programming & Scripting 22 March 2013 Hello World Bash Shell Script First you need to find out where is your bash interpreter located. Enter the following into your command
More informationCOMP 4/6262: Programming UNIX
COMP 4/6262: Programming UNIX Lecture 12 shells, shell programming: passing arguments, if, debug March 13, 2006 Outline shells shell programming passing arguments (KW Ch.7) exit status if (KW Ch.8) test
More informationCOMS 6100 Class Notes 3
COMS 6100 Class Notes 3 Daniel Solus September 1, 2016 1 General Remarks The class was split into two main sections. We finished our introduction to Linux commands by reviewing Linux commands I and II
More informationAssignment clarifications
Assignment clarifications How many errors to print? at most 1 per token. Interpretation of white space in { } treat as a valid extension, involving white space characters. Assignment FAQs have been updated.
More informationShell scripting Scripting and Computer Environment - Lecture 5
Shell scripting Scripting and Computer Environment - Lecture 5 Saurabh Barjatiya International Institute Of Information Technology, Hyderabad 28 July, 2011 Contents 1 Contents 1 Shell scripting with bash
More informationLast Time. on the website
Last Time on the website Lecture 6 Shell Scripting What is a shell? The user interface to the operating system Functionality: Execute other programs Manage files Manage processes Full programming language
More informationProcesses and Shells
Shell ls pico httpd CPU Kernel Disk NIC Processes Processes are tasks run by you or the OS. Processes can be: shells commands programs daemons scripts Shells Processes operate in the context of a shell.
More informationBourne Shell Reference
> Linux Reviews > Beginners: Learn Linux > Bourne Shell Reference Bourne Shell Reference found at Br. David Carlson, O.S.B. pages, cis.stvincent.edu/carlsond/cs330/unix/bshellref - Converted to txt2tags
More informationINTRODUCTION TO SHELL SCRIPTING ITPART 2
INTRODUCTION TO SHELL SCRIPTING ITPART 2 Dr. Jeffrey Frey University of Delaware, version 2 GOALS PART 2 Shell plumbing review Standard files Redirection Pipes GOALS PART 2 Command substitution backticks
More information1. Hello World Bash Shell Script. Last Updated on Wednesday, 13 April :03
1 of 18 21/10/2554 9:39 Bash scripting Tutorial tar -czf myhome_directory.tar.gz /home/linuxcong Last Updated on Wednesday, 13 April 2011 08:03 Article Index 1. Hello World Bash Shell Script 2. Simple
More informationCommand Interpreters. command-line (e.g. Unix shell) On Unix/Linux, bash has become defacto standard shell.
Command Interpreters A command interpreter is a program that executes other programs. Aim: allow users to execute the commands provided on a computer system. Command interpreters come in two flavours:
More information5/8/2012. Exploring Utilities Chapter 5
Exploring Utilities Chapter 5 Examining the contents of files. Working with the cut and paste feature. Formatting output with the column utility. Searching for lines containing a target string with grep.
More informationEssentials for Scientific Computing: Bash Shell Scripting Day 3
Essentials for Scientific Computing: Bash Shell Scripting Day 3 Ershaad Ahamed TUE-CMS, JNCASR May 2012 1 Introduction In the previous sessions, you have been using basic commands in the shell. The bash
More information12.1 UNDERSTANDING UNIX SHELL PROGRAMMING LANGUAGE: AN INTRODUCTION Writing a Simple Script Executing a Script
12 Shell Programming This chapter concentrates on shell programming. It explains the capabilities of the shell as an interpretive high-level language. It describes shell programming constructs and particulars.
More informationShells and Shell Programming
Shells and Shell Programming 1 Shells A shell is a command line interpreter that is the interface between the user and the OS. The shell: analyzes each command determines what actions are to be performed
More informationBash Programming. Student Workbook
Student Workbook Bash Programming Published by ITCourseware, LLC, 7245 South Havana Street, Suite 100, Englewood, CO 80112 Contributing Authors: Julie Johnson, Rob Roselius Editor: Jeff Howell Special
More informationUNIX II:grep, awk, sed. October 30, 2017
UNIX II:grep, awk, sed October 30, 2017 File searching and manipulation In many cases, you might have a file in which you need to find specific entries (want to find each case of NaN in your datafile for
More informationShell Programming (bash)
Shell Programming Shell Programming (bash) Commands run from a file in a subshell A great way to automate a repeated sequence of commands. File starts with #!/bin/bash absolute path to the shell program
More informationПрограмиранев UNIX среда
Програмиранев UNIX среда Използванена команден шел и създаванена скриптове: tcsh, bash, awk, python Shell programming As well as using the shell to run commands you can use its built-in programming language
More informationECE 364 Software Engineering Tools Lab. Lecture 2 Bash II
ECE 364 Software Engineering Tools Lab Lecture 2 Bash II 1 Lecture 2 Summary Arrays I/O Redirection Pipes Quotes Capturing Command Output Commands: cat, head, tail, cut, paste, wc 2 Array Variables Declaring
More informationsottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi
Titolo presentazione Piattaforme Software per la Rete sottotitolo BASH Scripting Milano, XX mese 20XX A.A. 2016/17, Alessandro Barenghi Outline 1) Introduction to BASH 2) Helper commands 3) Control Flow
More informationCSE 15L Winter Midterm :) Review
CSE 15L Winter 2015 Midterm :) Review Makefiles Makefiles - The Overview Questions you should be able to answer What is the point of a Makefile Why don t we just compile it again? Why don t we just use
More informationUnix as a Platform Exercises + Solutions. Course Code: OS 01 UNXPLAT
Unix as a Platform Exercises + Solutions Course Code: OS 01 UNXPLAT Working with Unix Most if not all of these will require some investigation in the man pages. That's the idea, to get them used to looking
More informationLinux shell programming for Raspberry Pi Users - 2
Linux shell programming for Raspberry Pi Users - 2 Sarwan Singh Assistant Director(S) NIELIT Chandigarh 1 SarwanSingh.com Education is the kindling of a flame, not the filling of a vessel. - Socrates SHELL
More information5/20/2007. Touring Essential Programs
Touring Essential Programs Employing fundamental utilities. Managing input and output. Using special characters in the command-line. Managing user environment. Surveying elements of a functioning system.
More informationbash Args, Signals, Functions Administrative Shell Scripting COMP2101 Fall 2017
bash Args, Signals, Functions Administrative Shell Scripting COMP2101 Fall 2017 Positional Arguments It is quite common to allow the user of a script to specify what the script is to operate on (e.g. a
More informationScripting. More Shell Scripts. Adapted from Practical Unix and Programming Hunter College
Scripting More Shell Scripts Adapted from Practical Unix and Programming Hunter College Copyright 2006 2009 Stewart Weiss Back to shell scripts Now that you've learned a few commands and can edit files,
More informationBasic Linux (Bash) Commands
Basic Linux (Bash) Commands Hint: Run commands in the emacs shell (emacs -nw, then M-x shell) instead of the terminal. It eases searching for and revising commands and navigating and copying-and-pasting
More informationOutput with printf Input. from a file from a command arguments from the command read
More Scripting 1 Output with printf Input from a file from a command arguments from the command read 2 A script can test whether or not standard input is a terminal [ -t 0 ] What about standard output,
More informationShell Scripting. With Applications to HPC. Edmund Sumbar Copyright 2007 University of Alberta. All rights reserved
AICT High Performance Computing Workshop With Applications to HPC Edmund Sumbar research.support@ualberta.ca Copyright 2007 University of Alberta. All rights reserved High performance computing environment
More informationMore Scripting Todd Kelley CST8207 Todd Kelley 1
More Scripting Todd Kelley kelleyt@algonquincollege.com CST8207 Todd Kelley 1 Arithmetic Output with printf Input from a file from a command CST8177 Todd Kelley 2 A script can test whether or not standard
More informationShells and Shell Programming
Shells and Shell Programming Shells A shell is a command line interpreter that is the interface between the user and the OS. The shell: analyzes each command determines what actions are to be performed
More informationSHELL SCRIPT BASIC. UNIX Programming 2014 Fall by Euiseong Seo
SHELL SCRIPT BASIC UNIX Programming 2014 Fall by Euiseong Seo Shell Script Interactive shell sequentially executes a series of commands Some tasks are repetitive and automatable They are what programs
More informationCOMP 2718: Shell Scripts: Part 1. By: Dr. Andrew Vardy
COMP 2718: Shell Scripts: Part 1 By: Dr. Andrew Vardy Outline Shell Scripts: Part 1 Hello World Shebang! Example Project Introducing Variables Variable Names Variable Facts Arguments Exit Status Branching:
More informationCSCI 2132: Software Development. Norbert Zeh. Faculty of Computer Science Dalhousie University. Shell Scripting. Winter 2019
CSCI 2132: Software Development Shell Scripting Norbert Zeh Faculty of Computer Science Dalhousie University Winter 2019 Reading Glass and Ables, Chapter 8: bash Your Shell vs Your File Manager File manager
More informationUseful Unix Commands Cheat Sheet
Useful Unix Commands Cheat Sheet The Chinese University of Hong Kong SIGSC Training (Fall 2016) FILE AND DIRECTORY pwd Return path to current directory. ls List directories and files here. ls dir List
More informationc) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.
2.1 Introduction (No questions.) 2.2 A Simple Program: Printing a Line of Text 2.1 Which of the following must every C program have? (a) main (b) #include (c) /* (d) 2.2 Every statement in C
More informationEECS2301. Lab 1 Winter 2016
EECS2301 Lab 1 Winter 2016 Lab Objectives In this lab, you will be introduced to the Linux operating system. The basic commands will be presented in this lab. By the end of you alb, you will be asked to
More informationShell Scripting. Todd Kelley CST8207 Todd Kelley 1
Shell Scripting Todd Kelley kelleyt@algonquincollege.com CST8207 Todd Kelley 1 If we have a set of commands that we want to run on a regular basis, we could write a script A script acts as a Linux command,
More informationIntroduction: What is Unix?
Introduction Introduction: What is Unix? An operating system Developed at AT&T Bell Labs in the 1960 s Command Line Interpreter GUIs (Window systems) are now available Introduction: Unix vs. Linux Unix
More informationIntroduction to UNIX Part II
T H E U N I V E R S I T Y of T E X A S H E A L T H S C I E N C E C E N T E R A T H O U S T O N S C H O O L of H E A L T H I N F O R M A T I O N S C I E N C E S Introduction to UNIX Part II For students
More informationCS Unix Tools & Scripting
Cornell University, Spring 2014 1 February 24, 2014 1 Slides evolved from previous versions by Hussam Abu-Libdeh and David Slater A note on awk for (item in array) The order in which items are returned
More informationUnix Scripts and Job Scheduling. Overview. Running a Shell Script
Unix Scripts and Job Scheduling Michael B. Spring Department of Information Science and Telecommunications University of Pittsburgh spring@imap.pitt.edu http://www.sis.pitt.edu/~spring Overview Shell Scripts
More informationShells. A shell is a command line interpreter that is the interface between the user and the OS. The shell:
Shells A shell is a command line interpreter that is the interface between the user and the OS. The shell: analyzes each command determines what actions are to be performed performs the actions Example:
More informationS E C T I O N O V E R V I E W
AN INTRODUCTION TO SHELLS S E C T I O N O V E R V I E W Continuing from last section, we are going to learn about the following concepts: understanding quotes and escapes; considering the importance of
More informationGetting to grips with Unix and the Linux family
Getting to grips with Unix and the Linux family David Chiappini, Giulio Pasqualetti, Tommaso Redaelli Torino, International Conference of Physics Students August 10, 2017 According to the booklet At this
More informationIntroduction to Linux
Introduction to Linux The command-line interface A command-line interface (CLI) is a type of interface, that is, a way to interact with a computer. Window systems, punched cards or a bunch of dials, buttons
More informationWindshield. Language Reference Manual. Columbia University COMS W4115 Programming Languages and Translators Spring Prof. Stephen A.
Windshield Language Reference Manual Columbia University COMS W4115 Programming Languages and Translators Spring 2007 Prof. Stephen A. Edwards Team members Wei-Yun Ma wm2174 wm2174@columbia.edu Tony Wang
More informationChapter 4. Unix Tutorial. Unix Shell
Chapter 4 Unix Tutorial Users and applications interact with hardware through an operating system (OS). Unix is a very basic operating system in that it has just the essentials. Many operating systems,
More informationSHELL SCRIPT BASIC. UNIX Programming 2015 Fall by Euiseong Seo
SHELL SCRIPT BASIC UNIX Programming 2015 Fall by Euiseong Seo Shell Script! Interactive shell sequentially executes a series of commands! Some tasks are repetitive and automatable! They are what programs
More informationBash Reference Manual Reference Documentation for Bash Edition 2.5b, for Bash Version 2.05b. July 2002
.tex Bash Reference Manual Reference Documentation for Bash Edition 2.5b, for Bash Version 2.05b. July 2002 Chet Ramey, Case Western Reserve University Brian Fox, Free Software Foundation Copyright c 1991-2002
More informationLinux Shell Scripting. Linux System Administration COMP2018 Summer 2017
Linux Shell Scripting Linux System Administration COMP2018 Summer 2017 What is Scripting? Commands can be given to a computer by entering them into a command interpreter program, commonly called a shell
More informationbash, part 3 Chris GauthierDickey
bash, part 3 Chris GauthierDickey More redirection As you know, by default we have 3 standard streams: input, output, error How do we redirect more than one stream? This requires an introduction to file
More informationIntroduction to UNIX. Logging in. Basic System Architecture 10/7/10. most systems have graphical login on Linux machines
Introduction to UNIX Logging in Basic system architecture Getting help Intro to shell (tcsh) Basic UNIX File Maintenance Intro to emacs I/O Redirection Shell scripts Logging in most systems have graphical
More informationUnix Shell scripting. Dr Alun Moon 7th October Introduction. Notation. Spaces
Unix Shell scripting Dr Alun Moon 7th October 2017 Introduction Shell scripts in Unix are a very powerfull tool, they form much of the standard system as installed. What are these good for? So many file
More informationExamples: Directory pathname: File pathname: /home/username/ics124/assignments/ /home/username/ops224/assignments/assn1.txt
ULI101 Week 03 Week Overview Absolute and relative pathnames File name expansion Shell basics Command execution in detail Recalling and editing previous commands Quoting Pathnames A pathname is a list
More informationLecture 8. Introduction to Shell Programming. COP 3353 Introduction to UNIX
Lecture 8 Introduction to Shell Programming COP 3353 Introduction to UNIX 1 What is a shell script? An executable file containing Unix shell commands Programming control constructs (if, then, while, until,
More informationShell Programming Systems Skills in C and Unix
Shell Programming 15-123 Systems Skills in C and Unix The Shell A command line interpreter that provides the interface to Unix OS. What Shell are we on? echo $SHELL Most unix systems have Bourne shell
More informationEECS2301. 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
Warning: These notes are not complete, it is a Skelton that will be modified/add-to in the class. If you want to us them for studying, either attend the class or get the completed notes from someone who
More informationEssential Linux Shell Commands
Essential Linux Shell Commands Special Characters Quoting and Escaping Change Directory Show Current Directory List Directory Contents Working with Files Working with Directories Special Characters There
More informationBash Reference Manual
Bash Reference Manual Reference Documentation for Bash Edition 3.1-beta1, for Bash Version 3.1-beta1. September 2005 Chet Ramey, Case Western Reserve University Brian Fox, Free Software Foundation This
More informationbash Execution Control COMP2101 Winter 2019
bash Execution Control COMP2101 Winter 2019 Bash Execution Control Scripts commonly can evaluate situations and make simple decisions about actions to take Simple evaluations and actions can be accomplished
More informationIntroduction to Shell Scripting
Introduction to Shell Scripting Evan Bollig and Geoffrey Womeldorff Presenter Yusong Liu Before we begin... Everyone please visit this page for example scripts and grab a crib sheet from the front http://www.scs.fsu.edu/~bollig/techseries
More informationWriting Shell Scripts part 1
Writing Shell Scripts part 1 EECS 2031 21 November 2016 1 What Is a Shell? A program that interprets your request to run other programs Most common Unix shells: Bourne shell (sh) C shell (csh) Korn shell
More informationLab 4: Shell scripting
Lab 4: Shell scripting Comp Sci 1585 Data Structures Lab: Tools Computer Scientists Outline 1 2 3 4 5 6 What is shell scripting good? are the duct tape and bailing wire of computer programming. You can
More informationTitle:[ Variables Comparison Operators If Else Statements ]
[Color Codes] Environmental Variables: PATH What is path? PATH=$PATH:/MyFolder/YourStuff?Scripts ENV HOME PWD SHELL PS1 EDITOR Showing default text editor #!/bin/bash a=375 hello=$a #No space permitted
More informationAppendix A GLOSSARY. SYS-ED/ Computer Education Techniques, Inc.
Appendix A GLOSSARY SYS-ED/ Computer Education Techniques, Inc. $# Number of arguments passed to a script. $@ Holds the arguments; unlike $* it has the capability for separating the arguments. $* Holds
More informationCISC 220 fall 2011, set 1: Linux basics
CISC 220: System-Level Programming instructor: Margaret Lamb e-mail: malamb@cs.queensu.ca office: Goodwin 554 office phone: 533-6059 (internal extension 36059) office hours: Tues/Wed/Thurs 2-3 (this week
More informationThe Unix Shell & Shell Scripts
The Unix Shell & Shell Scripts You should do steps 1 to 7 before going to the lab. Use the Linux system you installed in the previous lab. In the lab do step 8, the TA may give you additional exercises
More informationFull file at C How to Program, 6/e Multiple Choice Test Bank
2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)
More informationShell 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
Shell Programming Shells A shell can be used in one of two ways: A command interpreter, used interactively A programming language, to write shell scripts (your own custom commands) Shell Scripts A shell
More information27-Sep CSCI 2132 Software Development Lab 4: Exploring bash and C Compilation. Faculty of Computer Science, Dalhousie University
Lecture 4 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lab 4: Exploring bash and C Compilation 27-Sep-2017 Location: Goldberg CS Building Time: Wednesday, 16:05
More informationBash Check If Command Line Parameter Exists
Bash Check If Command Line Parameter Exists How to enter the parameters on the command line for this shell script? exit 1 fi if $ERR, then echo $MSG exit 1 fi if ( -d "$NAME" ), then echo "Directory -
More informationIntroduction Variables Helper commands Control Flow Constructs Basic Plumbing. Bash Scripting. Alessandro Barenghi
Bash Scripting Alessandro Barenghi Dipartimento di Elettronica, Informazione e Bioingegneria Politecnico di Milano alessandro.barenghi - at - polimi.it April 28, 2015 Introduction The bash command shell
More informationHere redirection. Case statement. Advanced Unix Tools Lecture 6 CS214 Spring 2004 Friday March 5, 2004
Advanced Unix Tools Lecture 6 CS214 Spring 2004 Friday March, 2004 Here redirection Recall that redirection allows you to redirect the input to a command from a file (using
More informationScript Programming Systems Skills in C and Unix
Script Programming with Perl II 15-123 Systems Skills in C and Unix Subroutines sub sum { return $a + $b; } So we can call this as: $a = 12; $b = 10; $sum = sum(); print the sum is $sum\n ; Passing Arguments
More informationA Big Step. Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers
A Big Step Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers Copyright 2006 2009 Stewart Weiss What a shell really does Here is the scoop on shells. A shell is a program
More informationLecture 5. Essential skills for bioinformatics: Unix/Linux
Lecture 5 Essential skills for bioinformatics: Unix/Linux UNIX DATA TOOLS Text processing with awk We have illustrated two ways awk can come in handy: Filtering data using rules that can combine regular
More informationCSE II-Sem)
1 2 a) Login to the system b) Use the appropriate command to determine your login shell c) Use the /etc/passwd file to verify the result of step b. d) Use the who command and redirect the result to a file
More informationMy Favorite bash Tips and Tricks
1 of 6 6/18/2006 7:44 PM My Favorite bash Tips and Tricks Prentice Bisbal Abstract Save a lot of typing with these handy bash features you won't find in an old-fashioned UNIX shell. bash, or the Bourne
More informationLecture 02 The Shell and Shell Scripting
Lecture 02 The Shell and Shell Scripting In this course, we need to be familiar with the "UNIX shell". We use it, whether bash, csh, tcsh, zsh, or other variants, to start and stop processes, control the
More informationGrep and Shell Programming
Grep and Shell Programming Comp-206 : Introduction to Software Systems Lecture 7 Alexandre Denault Computer Science McGill University Fall 2006 Teacher's Assistants Michael Hawker Monday, 14h30 to 16h30
More informationScripting. Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers
Scripting Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers Adapted from Practical Unix and Programming Hunter College Copyright 2006 2009 Stewart Weiss What a shell
More informationToday. 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?
Today Unix as an OS case study Intro to Shell Scripting Make sure the computer is in Linux If not, restart, holding down ALT key Login! Posted slides contain material not explicitly covered in class 1
More informationSystem Programming. Session 6 Shell Scripting
System Programming Session 6 Shell Scripting Programming C Programming vs Shell Programming C vs Shell Programming Compilation/Direct execution C Requires compilation while shell script can be directly
More informationLinux Command Line Interface. December 27, 2017
Linux Command Line Interface December 27, 2017 Foreword It is supposed to be a refresher (?!) If you are familiar with UNIX/Linux/MacOS X CLI, this is going to be boring... I will not talk about editors
More informationAdvanced Unix Programming Module 03 Raju Alluri spurthi.com
Advanced Unix Programming Module 03 Raju Alluri askraju @ spurthi.com Advanced Unix Programming: Module 3 Shells & Shell Programming Environment Variables Writing Simple Shell Programs (shell scripts)
More informationAppendix B WORKSHOP. SYS-ED/ Computer Education Techniques, Inc.
Appendix B WORKSHOP SYS-ED/ Computer Education Techniques, Inc. 1 Introduction There are no workshops for this chapter. The instructor will provide demonstrations and examples. SYS-ED/COMPUTER EDUCATION
More informationTable Of Contents. 1. Zoo Information a. Logging in b. Transferring files 2. Unix Basics 3. Homework Commands
Table Of Contents 1. Zoo Information a. Logging in b. Transferring files 2. Unix Basics 3. Homework Commands Getting onto the Zoo Type ssh @node.zoo.cs.yale.edu, and enter your netid pass when prompted.
More informationAutomating Tasks Using bash
Overview Automating Tasks Using bash SHARCNET Introduction to command shells & bash bash fundamentals I/O redirection, pipelining, wildcard expansion, shell variables Shell scripting writing bash scripts
More information/smlcodes /smlcodes /smlcodes. Shell Scripting TUTORIAL. Small Codes. Programming Simplified. A SmlCodes.Com Small presentation
/smlcodes /smlcodes /smlcodes Shell Scripting TUTORIAL Small Codes Programming Simplified A SmlCodes.Com Small presentation In Association with Idleposts.com For more tutorials & Articles visit SmlCodes.com
More informationCOSC2031 Software Tools Introduction to C
COSC2031 Software Tools Introduction to C Instructor: Matt Robinson matt@cs.yorku.ca http://www.cs.yorku.ca/course/2031/ From Last Day What this course is about A (brief) History of Unix and C Some sample
More information