Linux Administration Working with the BASH Shell.

Slides:



Advertisements
Similar presentations
A Guide to Unix Using Linux Fourth Edition
Advertisements

1 © 2001 John Urrutia. All rights reserved. Chapter 5 The Shell Overview.
CS 497C – Introduction to UNIX Lecture 22: - The Shell Chin-Chih Chang
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Linux+ Guide to Linux Certification, Second Edition
Shell Basics CS465 - Unix. Shell Basics Shells provide: –Command interpretation –Multiple commands on a single line –Expansion of wildcard filenames –Redirection.
Now, return to the Unix Unix shells: Subshells--- Variable---1. Local 2. Environmental.
Linux+ Guide to Linux Certification, Second Edition
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
Guide to Linux Installation and Administration, 2e1 Chapter 6 Using the Shell and Text Files.
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
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, or Scripting Shirley Moore CPS 5401 Fall August 29,
Chapter Seven Advanced Shell Programming. 2 Lesson A Developing a Fully Featured Program.
Advanced Shell Programming. 2 Objectives Use techniques to ensure a script is employing the correct shell Set the default shell Configure Bash login and.
Agenda Control Flow Statements Purpose test statement if / elif / else Statements for loops while vs. until statements case statement break vs. continue.
Introduction to Shell Script Programming
Week 7 Working with the BASH Shell. Objectives  Redirect the input and output of a command  Identify and manipulate common shell environment variables.
Agenda User Profile File (.profile) –Keyword Shell Variables Linux (Unix) filters –Purpose –Commands: grep, sort, awk cut, tr, wc, spell.
Chapter Four UNIX File Processing. 2 Lesson A Extracting Information from Files.
– Introduction to the Shell 10/1/2015 Introduction to the Shell – Session Introduction to the Shell – Session 2 · Permissions · Users.
An Introduction to Unix Shell Scripting
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 8 Shell.
The UNIX Shell. The Shell Program that constantly runs at terminal after a user has logged in. Prompts the user and waits for user input. Interprets command.
Linux+ Guide to Linux Certification, Third Edition
Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.
Week 3 Exploring Linux Filesystems. Objectives  Understand and navigate the Linux directory structure using relative and absolute pathnames  Describe.
Introduction to Bash Programming Ellen Zhang. Previous three classes What have we learnt so far ?
Linux+ Guide to Linux Certification, Third Edition
Linux Operations and Administration
Basic Shell Scripting - Part 1 Objective - Learn to: Read Start-up Files Edit Start-up Files Modify Your User Environment Communicate with Users Write.
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.
CS465 - UNIX The Bourne Shell.
Shell Programming. Introducing UNIX Shells  Shell is also a programming language and provides various features like variables, branching, looping and.
Workbook 6 – Part 2 The Bash Shell
Linux+ Guide to Linux Certification Chapter Eight Working with the BASH Shell.
CSC 352– Unix Programming, Spring 2015 March 2015 Shell Programming (Highlights only)
Shell Programming. Creating Shell Scripts: Some Basic Principles A script name is arbitrary. Choose names that make it easy to quickly identify file function.
Unix/Linux cs3353. The Shell The shell is a program that acts as the interface between the user and the kernel. –The shell is fully programmable and will.
Writing Scripts Hadi Otrok COEN 346.
Shell Programming Learning Objectives: 1. To understand the some basic utilities of UNIX File 2. To compare UNIX shell and popular shell 3. To learn the.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
1 © 2000 John Urrutia. All rights reserved. Session 5 The Bourne Shell.
Chapter Six Introduction to Shell Script Programming.
Week 9 - Nov 7, Week 9 Agenda I/O redirection I/O redirection pipe pipe tee tee.
Executable scripts. So far We have made scripts echo hello #for example And called it hello.sh Run it as sh hello.sh This only works from current directory?
Lesson 3-Touring Utilities and System Features. Overview Employing fundamental utilities. Linux terminal sessions. Managing input and output. Using special.
Agenda Positional Parameters / Continued... Command Substitution Bourne Shell / Bash Shell / Korn Shell Mathematical Expressions Bourne Shell / Bash Shell.
CSCI 330 UNIX and Network Programming Unit III Shell, Part 1.
Linux+ Guide to Linux Certification, Second Edition Chapter 4 Exploring Linux Filesystems.
Linux+ Guide to Linux Certification, Second Edition
Introduction to Bash Shell. What is Shell? The shell is a command interpreter. It is the layer between the operating system kernel and the user.
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]
Shell Scripting September 27, 2004 Class Meeting 6, Part II * Notes adapted by Lenwood Heath from previous work by other members of the CS faculty at Virginia.
 Prepared by: Eng. Maryam Adel Abdel-Hady
Agenda Customizing a Unix/Linux account Environment Introduction to Start-up Files (.bash_profile,.bashrc,.profile,.kshrc) Safe Methods for Changing Start-up.
Lab 7 Shell Script Reference: Linux Shell Scripting Tutorial v1.05r3 A Beginner's handbook
Department of Computer Engineering
SUSE Linux Enterprise Desktop Administration
Shell Features CSCI N321 – System and Network Administration
CSC 352– Unix Programming, Fall 2012
CSE 303 Concepts and Tools for Software Development
Chapter Four UNIX File Processing.
Linux Shell Script Programming
CSC 352– Unix Programming, Fall, 2011
Introduction to Bash Programming, part 3
Basic shell scripting CS 2204 Class meeting 7
Presentation transcript:

Linux Administration Working with the BASH Shell

2 Objectives Redirect the input and output of a command Identify and manipulate common shell environment variables Create and export new shell variables Edit environment files to create variables upon shell startup

3 Objectives (continued) Describe the purpose and nature of shell scripts Create and execute basic shell scripts Effectively use common decision constructs in shell scripts

4 Command Input and Output BASH shell responsible for: –Providing user interface –Interpreting commands –Manipulating command input and output Provided user specifies certain shell metacharacters with command File descriptors: Numeric labels that define command input and command output

5 Command Input and Output (continued) Standard Input (stdin): File descriptor representing command input Standard Output (stdout): File descriptor representing command output Standard Error (stderror): File descriptor representing command error messages

6 Command Input and Output (continued) The three common file descriptors

7 Redirection Redirect stdout and stderr from terminal screen to a file –Use “>” shell metacharacter –Can redirect stdout and stderr to separate files Use separate filenames for stdout and stderr

8 Redirection (continued) Redirecting stdin to a file: –Use “<“ shell metacharacter tr command: Replace characters in a file sent via stdin

9 Redirection (continued) Common redirection examples

10 Pipes Send stdout of one command to another command as stdin Pipe: String of commands connected by “|” metacharacters –stdout on left, stdin on right Commonly used to reduce amount of information displayed on terminal screen

11 Pipes (continued) Figure : Piping information from one command to another

12 Pipes (continued) Can use multiple pipes on command line –Pass information from one command to another over a series of commands filter commands: Commands that can take from stdin and give to stdout –Can be on either side of a pipe tee commands: Filter commands that also send information to a file

13 Pipes (continued) Piping several commands

14 Shell Variables Variable: A reserved portion of memory containing accessible information BASH shell has several variables in memory Environment variables: Contain information that system and programs access regularly User-defined variables: Custom variables define by users Special variables –Useful when executing commands and creating new files and directories

15 Environment Variables set command: Lists environment variables and current values echo command: View contents a specified variable –Use $ shell metacharacter Changing value of a variable: –Specify variable name followed by equal sign (=) and new value

16 Environment Variables (continued) Common BASH environment variables

17 Environment Variables (continued) (continued): Common BASH environment variables

18 Environment Variables (continued) Table (continued): Common BASH environment variables

19 User-Defined Variables Variable identifier: Name of a variable Creating new variables: –Specify variable identifier followed by equal sign and the new contents Features of variable identifiers: –Can contain alphanumeric characters, dash characters, or underscore characters –Must not start with a number –Typically capitalized to follow convention

20 User-Defined Variables (continued) Subshell: Shell created by current shell –Most shell commands run in a subshell –Variables created in current shell are not available to subshells export command: Exports user-defined variables to subshells –Ensures that programs started by current shell have access to variables env command: Lists all exported environment and user-defined variables in a shell

21 Other Variables Not displayed by set or env commands –Perform specialized functions in the shell –e.g., UMASK variable alias command: Creates shortcuts to commands –Use unique alias names –Aliases stored in special variables –Can create single alias to multiple commands Use ; metacharacter

22 Environment Files When exiting BASH shell, all stored variables are destroyed Environment files: Store variables and values –Executed each time BASH shell is started –Ensures variables are always accessible

23 Environment Files (continued) Common BASH shell environment files (in order they are executed): –/etc/profile –~/.bash_profile –~/.bash_login –~/.profile Hidden environment files allow users to set customized variables

24 Environment Files (continued) To add a variable, add a line to environment file –Use command line syntax Any command can be placed inside any environment file –e.g., alias creation.bashrc (BASH run-time configuration): First hidden environment file executed at login

25 Shell Scripts Shell script: Text file containing a list of commands or constructs for shell to execute –May contain any command that can be entered on command line Hashpling: First line in a shell script –Defines which shell is used to interpret shell script commands

26 Shell Scripts (continued) Executing shell scripts with read permission: –Start another BASH shell, specify the shell script as an argument Executing shell scripts with read/write permission: –Executed like any executable program

How to write shell script Use any editor like vi or vim to write shell script. After writing shell script set execute permission for your script as follows syntax: chmod 755 myscript1.sh (3) Execute your script as syntax:./myscript1.sh./ means current directory,. (dot) means execute given command file in current shell without starting the new copy of shell 27

My first Script Try $ vi first #!/bin/bash # My first shell script # clear echo “ Knowledge is Power“ After saving the above script, you can run the script as follows: $./first 28

Second Script $ vi ginfo #!bash/sh # Script to print user information who currently login, current date & time # clear echo "Hello $USER" echo "Today is \c ";date echo "Number of user login : \c" ; who | wc -l echo "Calendar" cal exit 0 29

30 Escape Sequences Character sequences having special meaning in the echo command –Prefixed by \ character –Must use –e option in echo command

31 Escape Sequences (continued) Table : Common echo escape sequences

32 Reading Standard Input Shell scripts may need input from user –Input may be stored in a variable for later use read command: Takes user input from stdin –Places in a variable specified by an argument to read command

33 Decision Constructs Most common type of construct used in shell scripts Alter flow of a program: –Based on whether a command completed successfully –Based on user input

Reading User Input (1/2) #!/bin/bash echo -e "Hi, please type the word: \c " read word echo "The word you entered is: $word" echo -e "Can you please enter two words? " read word1 word2 echo "Here is your input: \"$word1\" \"$word2\"" echo -e "How do you feel about bash scripting? " ----see next slides for the rest of the code 34

Reading User Input (2/2) # read command now stores a reply into the default build-in variable $REPLY read echo "You said $REPLY, I'm glad to hear that! " echo -e "What are your favorite colours ? " # -a makes read command to read into an array read -a colours echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)" 35

36 Decision Constructs (continued) Figure : A sample decision construct

37 Decision Constructs (continued) Figure 8-5: A sample decision construct

38 The if Construct Control flow of program based on true/false decisions Syntax:

39 The if Construct (continued) Common rules governing if constructs: –elif (else if) and else statements optional –Unlimited number of elif statements –do these commands section may consist of multiple commands One per line –do these commands section typically indented for readability –End of statement must be “if” –this is true may be a command or test statement

40 The if Construct (continued) test statement: Used to test a condition –Generates a true/false value –Inside of square brackets ( [ … ] ) Must have spaces after “[” and before “]” Special comparison operators: ––o (OR) ––a (AND) –! (NOT)

41 The if Construct (continued) Table : Common test statements

42 The if Construct (continued) Table : Special operators in test statements

If Else (String Comparison) #!/bin/bash #Declare string S1 S1="Bash" #Declare string S2 S2="Scripting" if [ $S1 = $S2 ]; then echo "Both Strings are equal" else echo "Strings are NOT equal" fi 43

If Else & Numeric Comparison Example-1 #!/bin/bash # declare integers NUM1=2 NUM2=2 if [ $NUM1 -eq $NUM2 ]; then echo "Both Values are equal" else echo "Values are NOT equal" fi 44

If Else & Numeric Comparison Example-2 #!/bin/bash # declare integers NUM1=2 NUM2=1 if [ $NUM1 -eq $NUM2 ]; then echo "Both Values are equal" else echo "Values are NOT equal" fi 45

46 The case Construct Compares value of a variable with several different patterns of text or numbers Syntax:

47 The case Construct (continued) If a match is found, commands to right of pattern are executed Must end with esac Sample Code : #!/bin/bash echo "What is your preferred programming / scripting language" echo "1) bash" echo "2) perl" echo "3) phyton"

echo "4) c++" echo "5) I do not know !" read case; #simple case bash structure # note in this case $case is variable and does not have to # be named case this is just an example case $case in 1) echo "You selected bash";; 2) echo "You selected perl";; 3) echo "You selected phyton";; 4) echo "You selected c++";; 5) exit esac 48

49 The && and || Constructs Time-saving shortcut constructs –When only one decision needs to be made during execution Syntax: –command && command –command || command

50 The && and || Constructs (continued) &&: Second command executed only if first completes successfully ||: Second command executed only if first fails

51 Summary Three components are available to commands: Standard Input, Standard Output, and Standard Error Standard Input is typically user input taken from the keyboard; Standard Output and Standard Error are sent to the terminal screen You can redirect the Standard Output and Standard Error of a command to a file using redirection symbols

52 Summary (continued) Use the pipe symbol to redirect the Standard Output from one command to the Standard Input of another Most variables available to the BASH shell are environment variables that are loaded into memory after login from environment files You can create your own variables in the BASH shell and export them so that they are available to programs started by the shell

53 Summary (continued) Shell scripts can be used to execute several Linux commands Decision constructs can be used in shell scripts to execute certain Linux commands based on user input or the results of a certain command