Linux Constructs. The default separator character between each integer is a newline, but this can be changed with the -s option.



Similar documents
Bash shell programming Part II Control statements

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

BASH Scripting. A bash script may consist of nothing but a series of command lines, e.g. The following helloworld.sh script simply does an echo.

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

Lecture 4: Writing shell scripts

Unix Scripts and Job Scheduling

Answers to Even-numbered Exercises

Advanced Bash Scripting. Joshua Malone

Introduction to Shell Scripting

PYTHON Basics

Lecture 2 Notes: Flow of Control

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Systems Programming & Scripting

Exercise 4 Learning Python language fundamentals

CS Unix Tools & Scripting Lecture 9 Shell Scripting

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

Hands-On UNIX Exercise:

Example of a Java program

Informatica e Sistemi in Tempo Reale

Visual Logic Instructions and Assignments

Python Lists and Loops

JavaScript: Control Statements I

F ahrenheit = 9 Celsius + 32

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

Eventia Log Parsing Editor 1.0 Administration Guide

HP-UX Essentials and Shell Programming Course Summary

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

PHP Tutorial From beginner to master

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Chapter 5 Programming Statements. Chapter Table of Contents

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

6. Control Structures

A Crash Course on UNIX

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 6 Program Control

Exercise 1: Python Language Basics

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

Unix Shell Scripting Tutorial Ashley J.S Mills

Pseudo code Tutorial and Exercises Teacher s Version

3.GETTING STARTED WITH ORACLE8i

Chapter 8 Selection 8-1

Introduction to Python

Python Loops and String Manipulation

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

J a v a Quiz (Unit 3, Test 0 Practice)

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Introduction to Shell Programming

Command Line - Part 1

Lab 1: Introduction to C, ASCII ART and the Linux Command Line Environment

Writing Control Structures

MATLAB Programming. Problem 1: Sequential

Lecture 22 The Shell and Shell Scripting

Install Java Development Kit (JDK) 1.8

Introduction to Python

SFTP SHELL SCRIPT USER GUIDE

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

CS 241 Data Organization Coding Standards

Programming Exercises

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Stacks. Linear data structures

5 Arrays and Pointers

PL / SQL Basics. Chapter 3

Chapter One Introduction to Programming

Selection Statements

Writing Shell Scripts in UNIX. A simple Bash-shell script. Comments and Commands

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

AN INTRODUCTION TO UNIX

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

Computer Science 217

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

ALGORITHMS AND FLOWCHARTS. By Miss Reham Tufail

CLC Server Command Line Tools USER MANUAL

Linux Shell Script To Monitor Ftp Server Connection

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

ALGORITHMS AND FLOWCHARTS

Computational Mathematics with Python

Two-way selection. Branching and Looping

Computational Mathematics with Python

Introduction to Java

Welcome to Introduction to programming in Python

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

ESPResSo Summer School 2012

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

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Conditions & Boolean Expressions

TIP: To access the WinRunner help system at any time, press the F1 key.

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Moving from CS 61A Scheme to CS 61B Java

Lab 4.4 Secret Messages: Indexing, Arrays, and Iteration

Programming Languages CIS 443

Automating admin tasks using shell scripts and cron Vijay Kumar Adhikari.

The Linux Operating System and Linux-Related Issues

Unit 1 Number Sense. In this unit, students will study repeating decimals, percents, fractions, decimals, and proportions.

PHP Debugging. Draft: March 19, Christopher Vickery

awk A UNIX tool to manipulate and generate formatted data

Transcription:

Linux Constructs Relational Operators -eq - Equal to -lt - Less than -gt - Greater than -ge - Greater than or Equal to -le - Less than or Equal to File related tests -f le - True if le exists and is a regular le. -r le - True if le exists and is readable. -w le - True if le exists and is writable. -x le - True if le exists and is executable. -d le - True if le exists and is a directory. -s le - True if le exists and has a size greater than zero. String tests -nstr - True if string str is not a null string. -zstr - True if string str is a null string. str1 == str2 - True if both strings are equal. str - True if string str is assigned a value and is not null. str1!= str2 - True if both strings are unequal. -s le - True if le exists and has a size greater than zero. Test also permits the checking of more than one expression in the same line. -a - Performs the AND function -o - Performs the OR function The seq command- prints numeric sequences Syntax: seq [OPTION]... LAST seq[option]... FIRST LAST seq[option]... FIRST INCREMENT LAST The default separator character between each integer is a newline, but this can be changed with the -s option. bash$ seq 5 1 2 3 4 5 bash$ seq -s : 5 1:2:3:4:5 More on the test command As we saw earlier, the test command is usually implemented using square bracket notation e.g. [ arguments ] 1

However there are some operators which may be used for special tests: $ [ -e lename ] && echo Filename exists The operator e examines the argument following and if that le exists, the command succeeds (exit status 0), or if it fails with an exit status 1. The following table lists the operators which may be used: -d lename True if the lename exists and is a directory -e lename True if the lename exists -f lename True if the lename exists and is regular -r lename True if the lename exists and is readable -s lename True if the lename exists and has size non-zero -w lename True if the lename exists and is writeable -x lename True if the lename exists and is executable A couple of rules about logical operators used as branches: If you write "test && command", the command will only be executed if the test succeeds. If you write "test command", the command will only be executed if the test fails. Try these tests: $ true&& echo "Yes." Yes. $ false echo "Yes." Yes. Notice that the outcomes are entirely in keeping with one's intuition about such logical comparisons, and all is well as long as you n't think about the fact that true equals 0. :) Here's another scheme commonly seen in shell script programming and interactive sessions: $ command1&& command2 && command3 && command4 This line of code will not run the next command in the sequence unless the prior command has returned "true", meaning no errors. It is a way to avoid running a command if a required prior outcome is not present. The if statement The general format for an if statement is: if [ condition is true ] execute these commands else execute those commands The else clause is optional, but you must end the construct with the command. You can also have nested if clauses by using the elif command like this: 2

Example if [ condition1 is true ] execute these commands elif [ condition2 is true ] execute these commands else execute those commands Here are some examples using the conditional expressions just listed. Note that the spaces on either side of the square brackets are not optional! if [ $price -gt 20000 ] else echo 'Too much.' echo 'Do you have one in blue?' For loops Examples For i in 1 2 3 4 5 echo "Welcome $i times" For i in{1..5} echo "Welcome $i times" The next script lists a sequence between 1 and 20 in steps of 2,. For i in $(seq 1 2 20) echo "Welcome $i times" The next script is similar the C programming construct for(( c=1; c<=5; c++)) echo "Welcome $c times..." The next script demonstrates an endless loop using the forloop. 3

for(( ; ; )) echo "innite loops [ hit CTRL+C to stop]" To perform an early exit with break statement inside the for loop or indeed a WHILE or UNTIL loop. The general break statement inside the for loop: for I in 1 2 3 4 5 statements1#executed for all values of I, up to a disaster-condition if any. statements2 if(disaster-condition) break #Abann the loop. statements3#while good and, no disaster-condition. The following for loop will be abann when /etc/resolv.conf le found. for le in /etc/* if[ "${le}" == "/etc/resolv.conf" ] ; countnameservers=$(grep c nameserver/etc/resolv.conf) echo "Total ${countnameservers} nameservers dened in ${le}" break Brace Expansion Bash brace expansion is used to generate stings at the command line or in a shell script. The syntax for brace expansion consists of either a sequence specication or a comma separated list of items inside curly braces "{}". A sequence consists of a starting and ending item separated by two periods "..". Some examples and what they expand to: {aa,bb,cc,dd} =>aa bb cc dd {0..12} => 0 1 2 3 4 5 6 7 8 9 10 11 12 {3..-2} => 3 2 1 0-1 -2 {a..g} =>a b c d e f g {g..a} =>g f e d c b a If the brace expansion has a prex or sufx string those strings are included in the expansion: a{0..3}b => a0b a1b a2b a3b Brace expansions can be nested: {a,b{1..3},c} => a b1 b2 b3 c 4

A counted for loop using brace expansion requires the least amount of typing: For i in {0..19} echo $i Using brace expansion is the only way to create a loop with non-numeric "indexes": For i in {a..z} echo $i Brace expansion can also be useful when passing multiple long pathnames to a command. Instead of typing: $rm /a/long/path/foo /a/long/path/bar You can simply type: $ rm /a/long/path/{foo,bar} Continuation with continue statement To resume the next iteration of the enclosing FOR, WHILE or UNTIL loop use continue statement. for I in 1 2 3 4 5 statements1#executed for all values of ''I'', tildisaster-condition if any. statements2 if(condition) continue#next iteration of I in the loop and skip statements3 statements3 While Loops x=1 while[ $x -le 5 ] echo "Welcome $x times" x=$(( $x + 1 )) Until Loops Similar to thewhile is until; the syntax is the same but instead of the condition needing to succeed for the loop to continue, the condition must fail for the loop to nish and will give a non- zero exit status. 5

COUNT=0 # bash until loop until [ $COUNT -gt 5 ]; echo Value of count is: $COUNT let COUNT=COUNT+1 The case Statement Bash provides a case statement that lets you compare a string with several possible values and execute a block of code when it nds a match. Below is the general format: case "$var" in value1) commands;; value2) commands;; *)commands;; esac Where * indicates any string of characters Example echo "What is your preferred programming / scripting language" echo "1) bash" echo "2) perl" echo "3) phyton" echo "4) c++" echo "5) I not know!" read language; #simple case bash structure case $language in 1) echo "You selected bash";; 2) echo "You selected perl";; 3) echo "You selected phyton";; 4) echo "You selected c++";; 5) exit esac echo Enter A, B or C read letter case $letter in A a)echo You entered A ;; B b)echo You entered B ;; C c)echo You entered C ;; *) echo You didn\ t enter A, B or C ;; esac Where A a means either upper OR lower case A. echo "Please talk to me..." while : 6

read INPUT_STRING case$input_string in hello)echo "Hello yourself!;; bye)echo "See you again!"break;; *)echo "Sorry, I n't understand";; esac echo echo "That's all folks!" Functions Functions are similar to subroutines and procedures in other programming languages. The main difference between a script and a function is that a new instance of the shell is started for a shell script, whereas functions run in the current instance of the shell. Functions are dened as follows: name () { list ; } Here, name is the name of the function and list is a list of commands. The list of commands, list, is referred to as the body of the function. The parentheses, ( and), that follow name are required. function hello { echo Hello! } You can call function by typing its name: A function may return a value in three ways: Change the state of a variable or variables Use the exit command to end the shell script Use the return command to end the function, and return the supplied value to the calling section of the shell script This is rather like C, in that exit stops the program, and return returns control to the caller. The difference is that a shell function cannot change its parameters, though it can change global parameters. #!/bin/sh myfunc() { echo "I was called as : $@" x=2 } 7

### Main script starts here echo "Script was called with $@" x=1 echo "x is $x" myfunc 1 2 3 echo "x is $x" The script, when called as scope.sh a b c, gives the following output: Aliases Script was called with a b c x is 1 I was called as : 1 2 3 x is 2 Functions are general purpose and can be quite long. A Similar mechanism to replace short command sequences is aliases: $ alias ll= ls l more To remove an alias type unalias ll. Using bc as a calculator The bc utility is a programmable calculator. It allows several types of calculations and provides simple looping logic. It is also much easier to read than the expr expression evaluator. To start bc, type bc at the command line. Once bc begins, you are using calculator until you type quit. Try the following example. $ bc 4+2 6 quit $ Using variables in bc Some versions of bc allow only single character variables, though later versions allow multi-character variable names. Notice that the assignments not result in any output from bc, it requires you to type an expression or variable without an assignment for it to be output to the screen. $ bc a=4 b=5 c=b-a c 1 quit $ The t variable holds the last output. In the following example the user enters 4+2 and bc outputs 6. Then the user enters. (t) and bc outputs 6, the value held in the temporary variable, again. The variable can itself be 8

used in an expression as in.+1, and bc outputs 7. Finally typing. (t) will again output 7 because the last output value, 7, has been assigned to. (t). $ bc 4+2 6..+1 7. 7 quit $ Using bc in shell scripts To use bc in shell scripts just write a string with echo and pipe it into the input of bc. To add two floating point numbers say 2.5 and 3.75, type the string in quotes 2.5+3.75 pipe it into the input of bc : echo "2.5+3.75" bc 6.25 The same can be for subtraction, division and multiplication. The scale variable determines the number of digits which follow the decimal point in your result. By default, the value of the scale variable is zero. This can be set by declaring scale before your calculation, as in the following division example: $ echo scale=25;57/43 bc 1.3255813953488372093023255 Square roots $ echo scale=30;sqrt(2) bc 1.414213562373095048801688724209 Powers $ echo 6^6 bc 46656 The use of brackets If you try to calculate this: $ echo 6^6^6 bc You will either get a screen full of numbers or an error message. You need to type: $ echo (6^6)^6 bc Whereas what you did type was interpreted as: $ echo 6^(6^6) bc 9

Example shell script echo "Enter a floating point number: " read a echo "Enter another floating point number: " read b echo "Addition: " echo "$a+$b" bc Exercises. 1. Write a script to prompt the user for two numbers, representing width and height of a rectangle in cm, and display the area of the rectangle both in square metres and in square inches ( 1 inch = 2.54 cm). Name this script "area.sh" 2. Create a bash shell script that reads in a number from the user. If the number is 1, print out the date. If the number is 2, list the les in the current directory. If the number is 3, print out who is currently logged onto the system. If the number is anything else, print out an error message and exit. Name this script "various.sh" 3. Create a bash shell script that reads any number of words from the command line and prints them out in reverse order. e.g. if your program is called reverse.sh you would type: brian$> reverse.sh Fred Ben Chris Mary Mustafa and it displays Mustafa Mary Chris Ben Fred Name this script "reverse.sh" 4. Develop a Unix shell script to input number of hours worked and pay rate and calculate the total pay, the social security amount (assume 5%), the net pay. Do this as a loop until the user enters zero for the number of hours worked (zero indicates that the program is to be terminated). 5. Write a Linux Bash shell script to compute the bonus for a salesperson as per the given pseucode. Convert the following pseucode into a Bash script: Read SalesPerson and QuarterlySales from the keyboard. Display an appropriate message regarding the bonus when the QuarterlySales for the SalesPerson falls within these ranges: 1,000,000 and above. Bonus = 1,500 100,000 to 999,999. Bonus = 750 99,999 and below : No Bonus Test the script with the following data: Narinder 67000 Bob 99000 Mohamed 100000 Lisa 250000 Sarah 999999 Mary 1000000 10

6. Write a shell script to create a le with write permissions to members in your group and others but at a specied time input by the owner (using the at command), removes the write permissions from all except the owner of the le and sends a message to stut stating that the le has closed. 7. One type of lottery involves picking six different numbers, in the range of 1-19. Write a script that generates six pseuranm numbers in this range, with no duplicates. The user will be prompted to input six numbers and the script will output the numbers of correct matches. The script will give the option of echoing the results to stut or saving them to a le, along with the date and time the player entered the nal number. All the programme should be clearly commented as outlined in the hanut marked How to cument shell scripts. The programs should contain comprehensive error checking where appropriate and screen dumps of the programs outputs including tests showing the outputs of all scenarios. e.g outputs when incorrect data is entered by the user. The highest grades will require the programs to be well written. This means the inclusion of functions, meaningful variable names, indentation etc. 11