Week 7 - Lecture notes 7 PDF

Title Week 7 - Lecture notes 7
Course Operating Systems Principles And Applications
Institution Kwantlen Polytechnic University
Pages 12
File Size 211.3 KB
File Type PDF
Total Downloads 108
Total Views 190

Summary

All of Week 7 notes for INFO 1211 operating systems....


Description

Week 8: The Bash Shell and Scripting Introduction • bash, which is the Bash shell (or Bourne Again shell), is an open source shell that is the default shell for most Linux distributions - it’s backwards compatible with the Bourne shell (sh) - other common shells include csh and tcsh (the C shell and “T C Shell”), as well as ksh and zsh (the Korn and Z shells) • the syntax used for the shells differ, but general programming concepts such as variables, conditionals and loops exist in all the shells • for complex shell programming, you may use Python or another higher-level language; it is possible, though, to do a considerable amount of coding using shell programs, or scripts Login Files • when you log in to a Linux bash shell, commands in the file .bash_profile are executed - such commands can include setting of shell variables, setting aliases, configuring the environment, and so on • it is also possible to launch a subshell from within the login shell - this can happen, for example, when a script (program) is launched - when a new Bash shell which is not the login shell is started, commands in .bashrc are executed instead • it’s normal to not separate your initialization commands into “what I want when I log in” and “what I want when I launch a shell that’s not my login shell” - instead, you put all the commands that you want executed into .bashrc - then, you put the following in .bash_profile: if [ -f ~/.bashrc]; then . ~/.bashrc fi - what this code says is “if there is a .bashrc file present, execute its contents” - that way, no matter whether you are starting a bash login shell or a subshell, the same commands will get executed • to summarize: - .bash_profile - .bashrc

contains code to run when you log in and bash starts contains code to run when a non-login bash shell is launched,

INFO 1211

Week 7 The Bash Shell and Scripting

Page 2 of 12

Introduction to Scripting • a script is like a batch file in DOS; it allows you to create a list of shell commands that can be stored in a file - when you want to execute the script, simply type its name - useful for automating frequent command sequences • the most basic of scripts is simply a list of one or more Linux commands • example: list contents of the root directory #!/bin/bash # Script to list root directory contents # # Usage: list # cd / ls - suppose that we create this script in a file called list - to execute the script, we have to give it execute permission, for example: chmod u+x list - we then can execute the script simply by typing list - the first line of the script starts with #! (no space), followed immediately by the full path of the script used to execute the shell; here, we specify that this is a Bash shell script - note that from any shell, you can execute a script written for a different shell - ex. use #!/bin/tcsh in the script’s first line, and even though you start from a Bash shell, the script is executed using the tcsh shell - any lines other than the first which start with a # are considered comments - as with all programs, it’s good to include comments throughout your script - the rest of the script is simply the commands we want to execute • when a script is executed, Linux runs it in a subshell, or child shell of your current shell - a subshell has its own current directory, so changing directories in a script doesn’t affect the parent shell’s current directory - note that if you start in your home directory and execute list, the script moves to the root as specified in a subshell, but when the script terminates, you are where you started • when you launch a script, you may include arguments on the command line - for example, suppose this is in lister #!/bin/bash # Display long listing of a file

INFO 1211

Week 7 The Bash Shell and Scripting

Page 3 of 12

# # Usage: lister fname # ls -l $1 - here, $1 refers to the 1st argument on the command line for the script - in this case, $ lister Looky would invoke ls -l on the Looky file - here are the special variables created when you invoke a shell script: - $0 the name of the shell script - $n the nth command line argument (ex. $1, $2, $3, etc.) - $* all the command line arguments (not including $0) - $# the number of arguments passed to the script - $$ the process ID (pid) of the subshell - you can also use suppose this is in lister #!/bin/bash # Display long listing of a file # # Usage: lister fname # ls -l $* - here, $* repeats any arguments which we could use when invoking the script - we could use $lister file1 , $lister file1 file2 or even $lister * • example: write a shell script called letrun, which allows execute permission to all users to the file specified in the command line #!/bin/bash # Allow execute permission for the file in the command line # # Usage: letrun fname # chmod a+x $1 echo Permission changed for $1 - to use the script to turn on execute permission for a file called script1, you could then type letrun script1 - how would the script behave differently if we used $* in the script instead of $1? • example: write a shell script called words, which uses wc to count the words in a specified file and prints out the message “ contains words.” #!/bin/bash

INFO 1211

Week 7 The Bash Shell and Scripting

Page 4 of 12

# Count the words in the given file # # Usage: words fname # echo $1 contains `wc -w < $1` words. - note the use of the backquotes to retrieve the outcome of the wc command - also note the use of redirection with the wc command; this suppresses wc’s usual printing out of the file name whose words are being counted • note that in using scripts, as well as using shells in general, you can enclose arguments in single quotes or double quotes, and that can affect a command’s behaviour (note that the $ represents the shell prompt; you only need type “x=2”, not “$ x=2”): $ echo 3 * 4 = 12 3 file1 file2 file3 4 = 12 $ echo "3 * 4 = 12" 3 * 4 = 12 - putting double quotes around something inhibits wildcard expansion - however, to inhibit wildcards, variable substitution ($) and command substitution (backquotes), use single quotes: $ echo "my name is $USER, date is `date`" my name is Kenward, date is Mon Mar 2 12:32:14 PDT 2020 $ echo 'my name is $USER, date is `date`' my name is $user, date is `date`

Handling Shell Variables in Bash • variables can be used without declaration, as is required in languages such as C++ or Java (note that the $ represents the shell prompt; you only need type “x=2”, not “$ x=2”) $ var=value

e.g.

$ x=2 $ file=input.txt $ name="Kenward Chin"

• when you want to access the contents of the variables, put a $ in front of the variable name $ echo $x 2 $ echo $file

This means “display the value stored in variable x”

INFO 1211

Week 7 The Bash Shell and Scripting

Page 5 of 12

input.txt $ echo $name Kenward Chin • if you forget to put the $ before the variable name, you will just get the variable name as output: $ echo file file • some variations on the basic $variable formula: ${var}

putting curly brackets around the variable name can be useful for separating the variable name from surrounding text; e.g. doing “echo $xing” and “echo ${x}ing” do different things

${var-word}

value is var if var is set, and word otherwise

${var+word}

value is word if var is set, and nothing otherwise

${var=word}

assigns word to var if it is not already set, and value is word

• some examples: $ x=Hello $ echo $x Hello

set x to the string “Hello” write out the value of x

$ echo $xthere

doesn’t write “Hellothere”, looks for a variable xthere

$ echo ${x}there Hellothere

write out x and “there” right after

$ echo ${x-Bye} Hello

x is set to Hello, so this writes its value

$ echo ${x+Bye} Bye

x is set to Hello, so this writes the text in the command

$ echo ${y-Bye} Bye

y is not set, so this writes the text in the command

$ echo ${y+Bye}

y is not set, so this writes out nothing

$ echo ${x=example} Hello

x is already set, its value is not changed by the command

$ echo $x Hello

INFO 1211

Week 7 The Bash Shell and Scripting

Page 6 of 12

$ echo ${y=example} example

y is not set, so the command puts “example” in y

$ echo $y example

y was set to “example” by the previous command,

$ echo ${var+'var is set'}

could use this to see if var is set

Arrays in Bash • the syntax for arrays is similar to that in languages such as C++ and Java: $ cols[0]=red $ cols[1]=green $ cols[2]=blue

set elements of the array one at a time

$ cols=(red green blue)

set all the elements of the array at once

• to access the contents of list variables, you have to use braces $ echo ${cols[0]} red

use ${var[i]} to access the ith element

$ echo ${cols[*]} red green blue

use ${var[*]} or ${var[@]} to access entire list

$ echo ${#cols[*]} 3

use ${#var[*]} or ${#var[@]} to count items in list

• if you omit the braces, you will get the first element followed by the [ ] text $ echo $cols[0] red[0] • you can add to a list and remove items from a list $ cols=(red green blue) $ cols=(${cols[@]} yellow) $ echo ${cols[@]} red green blue yellow $ cols[4]=magenta $echo ${cols[@]}

set the array to its existing elements plus yellow

set the 5th item to magenta

INFO 1211

Week 7 The Bash Shell and Scripting

Page 7 of 12

red green blue yellow magenta $ cols=(infrared ${cols[*]} yellow) $ echo ${cols[*]} infrared red green blue yellow magenta

set the array to infrared plus its existing elements

$ unset cols[2] list is indexed from 0, so this refers to green $ echo ${cols[*]} infrared red green blue yellow magenta

Scope of Variables in Bash • when you create a variable in a Bash shell, it is local to that shell; if you create a subshell, the variable values are not passed on to that shell unless you explicitly export them $ x=1 $ bash

creates a subshell, with a new set of shell variables

$ echo $x nothing is printed, because x exists only in the parent shell $ exit back in parent shell now $ export x $ bash $ echo $x 1

now it works!

- (note that Bash does not support exporting array variables) • variables in Bash can be made read-only, so they cannot be altered $ x=1 $ readonly x $ x=2 bash: x: readonly variable - note that if you export this variable, the variable’s value can be changed in the subshell • within a script, you may use the read command to get input from the user; for example: echo –n Enter your name: read username echo Nice to meet you, $username

INFO 1211

Week 7 The Bash Shell and Scripting

Page 8 of 12

Arithmetic in Bash • to do arithmetic in Bash, you must assign the result of an expression to a variable just as in other programming languages - you must enclose the entire expression in double parentheses $ $ $ $ 3

a=1 set a and b to 1 and 2, then add them together b=2 ((sum=$a+$b)) echo $sum

- if you omit the double parentheses, a string assignment is done $ sum=$a+$b $ echo $sum 1+2 • the “regular” arithmetic operators from languages like C++, Java, etc. can be used here - *, /, %, +, -, ++, --, +=, -=, *=, /* $ a=2 $ ((a++)) $ echo $a 3 Conditional Statements in Bash • Bash supports two basic conditional instructions: - case…in…esac - if…then…elif…then…else…fi • case word in pattern1 | pattern2 | pattern3 ) command list1 ;; pattern4 | pattern 5 ) command list2 ;; *) default command list esac

include multiple patterns separated by | if you wish the case will not work without ;; to separate cases

use *) for the default case

- case is the Bash equivalent of the C++ switch instruction

INFO 1211

Week 7 The Bash Shell and Scripting

Page 9 of 12

- example: hockey teams echo –n "What's your favourite team? " read team case $team in "Edmonton" | "Oilers") echo "The Greasers? Ew." ;; "Calgary" | "Flames") echo "Flame rhymes with lame." echo "I hate those guys." ;; "Vancouver" | "Canucks") echo "Greatest team in NHL history!" ;; *) echo "How nice for you." esac • if test1 ; then command list1 elif test2 ; then command list2 else command list3 fi

the ; before “then” is required use as many or as few “elif”s and command lists as required the else clause is also optional

- this form of if allows you to do as many comparisons in a row as you want, and Bash executes the first command list that corresponds to a matching expression - any comparisons involving numbers must be enclosed in double parentheses echo –n "Enter a score: " read score if (($score > 100)) ; then echo You lie elif (($score >= 50)) ; then echo Pass else echo Fail fi - an alternative for the double parentheses notation is to use square brackets (with spaces) around the comparison, and to use comparison codes instead of comparison symbols: if (($score > 100)) ; then if (($percent >= 50) ; then

if [ $score -gt 100 ] ; then if [ $percent –ge 50 ] ; then

INFO 1211

Week 7 The Bash Shell and Scripting

Page 10 of 12

if (($number < 0)) ; then if [ $number -lt 0] ; then - if you do this, the possible codes are -le, -lt, -eq, -ne, -gt, -ge - when using strings, you must use the square bracket notation, but you use the usual comparison symbols (make sure to put a space on either side of the symbol): echo –n "Enter a password: " # -n suppresses new line read password if [ $password == "12345" ] ; then echo Password accepted else echo Access denied fi - you can also create compound conditions using && and || if [ $country == Canada ] && (($age >= 18)) ; then... • another useful thing to know is that you can put special codes in front of a file name in a script, and the shell will give you a true/false value depending on the situation - for example, a script called alive that tells you if a file is present #!/bin/bash # Check to see if a file exists # # Usage: alive file # if [ -f $1 ] ; then echo Found the file else echo Did not find the file fi - some of the codes are as follows: - -d: is file an existing directory? - -e: does file exist? - -r: is file user-readable? - -w: is file user-writeable? - -x: is file user-executable?

Loops in the Bash Shell • Bash supports three basic looping instructions: - for…do…done - while…do…done

e.g. if [ -d $filename ] ; then … etc.

INFO 1211

Week 7 The Bash Shell and Scripting

Page 11 of 12

- until…do…done • for var in wordlist ; do command list done - this is like the foreach instruction in some languages, where the variable takes on successive values from the list of words each time through the loop - example: loop through a literal list for colour in red orange yellow ; do echo $colour done - note that you do not enclose the individual words in parentheses, as in csh - if you want to cycle through a list, you can do this as follows: cols=(red green blue) for colour in ${cols[*]} ; do echo $colour done - or to cycle through the list of arguments to the script for arg in $* ; do echo $arg done • while test ; do command list end - this is like a while loop in C++ or Java, but the test has to be in the same format as what was used for the if instruction: double parentheses for numerical comparisons, and square brackets for string comparisons - example: countdown “timer” i=10 while (($i > 0)) ; do echo –n ${i}... ((i--)) done echo "" echo "BLASTOFF!!!"

INFO 1211

Week 7 The Bash Shell and Scripting

Page 12 of 12

- example: interactive loop to prompt user until he/she wants to quit again=y while [ $again == y ] ; do echo –n "Enter file name: " read name wc $name echo –n "Go again (y/n)? " read again done • until test ; do command list end - this works just like while, but loops “until” the test evaluates to true; essentially, it is like while except it negates the test condition - example: countdown “timer” i=10 until (($i == 0)) ; do echo –n ${i}... ((i--)) done echo "" echo "BLASTOFF!!!"...


Similar Free PDFs