Linux+ Guide to Linux Certification, Third Edition Chapter 7 Working with the BASH Shell.

  • Published on
    02-Jan-2016

  • View
    212

  • Download
    0

Embed Size (px)

Transcript

  • Linux+ Guide to Linux Certification, Third EditionChapter 7Working with the BASH Shell

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*ObjectivesRedirect the input and output of a commandIdentify and manipulate common shell environment variablesCreate and export new shell variablesEdit environment files to create variables upon shell startup

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Objectives (continued)Describe the purpose and nature of shell scriptsCreate and execute basic shell scriptsEffectively use common decision constructs in shell scripts

    Linux+ Guide to Linux Certification, 3e

  • Command Input and OutputBASH shell responsible for:Providing user interface Interpreting commandsManipulating command input and outputProvided user specifies certain shell metacharacters alongside commandFile descriptors: numeric labels that represent command input and command outputLinux+ Guide to Linux Certification, 3e*

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Command Input and Output (continued)Standard input (stdin): file descriptor referring to information processed by the command during executionOften user input typed on keyboardStandard output (stdout): file descriptor referring to normal output of the commandDisplayed on terminalStandard error (stderror): file descriptor referring to error messages generated by the commandDisplayed on terminal

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Command Input and Output (continued)Figure 7-1: The three common file descriptors

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*RedirectionRedirect stdout and stderr from terminal screen to a file Use > shell metacharacterCan redirect stdout and stderr to separate files using file descriptor numbersUse separate filenames for stdout and stderrThe file is automatically created if it did not exist prior to redirection, and is overwritten if it did existUse >> to append additional output to an existing file

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Redirection (continued)Redirecting stdin to a file:Use
  • Linux+ Guide to Linux Certification, 3e*Redirection (continued)Table 7-1: Common redirection examples

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*PipesSend stdout of one command to another command as stdinPipe: String of commands connected by | metacharactersstdout on left, stdin on rightCommonly used to reduce amount of information displayed on terminal screen

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Pipes (continued)Figure 7-2: Piping information from one command to another

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Pipes (continued)Can use multiple pipes on command linePass information from one command to another over a series of commandsFilter commands: Commands that can take from stdin and give to stdoutCan be on either side of a pipetee command: Filter command that receives information from stdin and sends that information to a file, as well as to stdout

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Pipes (continued)Figure 7-3: Piping several commands

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Pipes (continued)Can combine redirection and pipingInput redirection must occur at beginning of pipe Output redirection must occur at end of pipesed command: filter command used to search for and replace text stringsCan be used to replace some or all appearances of the search term and to delete specific input linesawk command: filter command used to search for text and perform specified action on itUse -F option to set delimiters

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Pipes (continued)Table 7-2: Common filter commands

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Shell VariablesVariable: reserved portion of memory containing accessible informationBASH shell has several variables in memoryEnvironment variables: contain information that system and programs access regularlyUser-defined variables: custom variables define by usersSpecial variablesUseful when executing commands and creating new files and directories

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Environment Variablesset command: lists environment variables and current valuesecho command: view contents of a specified variablePrefix variable name with the $ shell metacharacterChanging value of a variable:Specify variable name followed by equal sign (=) and new valueHOME and PWD variables should not be changed

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Table 7-3: Common BASH environment variables

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Environment Variables (continued)Table 7-3 (continued): Common BASH environment variables

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*User-Defined VariablesVariable identifier: Name of a variableCreating new variables:Specify variable identifier followed by equal sign and the new contentsFeatures of variable identifiers:Can contain alphanumeric characters, dash characters, or underscore charactersMust not start with a numberTypically capitalized to follow convention

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*User-Defined Variables (continued)Subshell: shell created by current shellMost shell commands run in a subshellVariables created in current shell are not available to subshellsexport command: exports user-defined variables to subshells Ensures that programs started by current shell have access to variablesenv command: lists all exported environment and user-defined variables in a shell

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Other VariablesNot displayed by set or env commandsPerform specialized functions in the shelle.g., UMASK variablealias command: creates shortcuts to commandsUse unique alias namesAliases stored in special variablesCan create single alias to multiple commands which will be executed in sequenceUse ; metacharacter

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Environment FilesWhen exiting BASH shell, all stored variables are destroyedEnvironment files: store variables and valuesExecuted each time BASH shell is startedEnsures variables are always accessible

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Environment Files (continued)Common BASH shell environment files (in order in which they are executed):~/.bashrc/etc/profile~/.bash_profile~/.bash_login~/.profileHidden environment files allow users to set customized variables

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Environment Files (continued)To add a variable, add a line to environment fileUse command line syntaxAny command can be placed inside any environment filee.g., alias creation.bashrc (BASH run-time configuration): first hidden environment file executed at login

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Shell ScriptsShell script: text file containing a list of commands or constructs for shell to executeMay contain any command that can be entered on command lineHashpling: first line in a shell scriptSpecifies which shell is used to interpret shell script commands

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Shell Scripts (continued)Executing shell scripts with read permission: Start another BASH shell, specify the shell script as an argumentExecuting shell scripts with read/execute permission:Executed like any executable programUse echo command to add descriptions and spaces to script output

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Escape SequencesCharacter sequences having special meaning in the echo commandPrefixed by \ characterMust use e option in echo command

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Escape Sequences (continued)Table 7-4: Common echo escape sequences

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Reading Standard InputShell scripts may need input from userInput may be stored in a variable for later useread command: takes user input from stdin and places it in a variable Variable name specified by an argument to read command

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Decision ConstructsMost common type of construct used in shell scriptsAlter flow of a program:Based on whether a command completed successfullyBased on user input

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Decision Constructs (continued)Figure 7-4: A two-question decision construct

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Decision Constructs (continued)Figure 7-5: A command-based decision construct

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*The if ConstructControl flow of program based on true/false decisionsMost common type of decision constructSyntax:

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*The if Construct (continued)Common rules governing if constructs:elif (else if) and else statements are optionalUnlimited number of elif statementsDo these commands section may consist of multiple commandsOne per lineTypically indented for readabilityEnd of statement must be fiCondition (this is true portion) may be a command or test statement

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*The if Construct (continued)test statement: used to test a conditionGenerates a true/false valueInside of square brackets ( [ ] ) or prefixed by the word testMust have spaces after [ and before ]Special comparison operators: used to combine test statements: o (OR) a (AND)! (NOT)

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*The if Construct (continued)Table 7-5: Common test statements

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*The if Construct (continued)Table 7-6: Special operators in test statements

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*The case ConstructCompares value of a variable with several different patterns of text or numbersSyntax:

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*The case Construct (continued)If a match is found, commands to right of pattern are executedMust end with esac

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*The && and || ConstructsTime-saving shortcut constructsWhen only one decision needs to be made during executionSyntax:command && commandcommand || command&&: Second command executed only if first completes successfully||: Second command executed only if first fails

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*Loop ConstructsLoop constructs: execute commands repetitivelyAlter the flow of a program based on the results of a particular statementRepeat entire program until reach desired result

    Linux+ Guide to Linux Certification, 3e

  • The for ConstructCan be used to process a list of objectsSyntax: for var_name in string1 string2 do these commands doneDuring execution sets var_name to a string name, and executes the commands between do and done for that stringRepeats for all the stringsLinux+ Guide to Linux Certification, 3e*

    Linux+ Guide to Linux Certification, 3e

  • The while ConstructBegins with test statementCommands within the loop construct are executed as long as the test statement returns trueContains a counter variableValue changes with each iteration of the loopSyntax:while this returns true do these commands doneLinux+ Guide to Linux Certification, 3e*

    Linux+ Guide to Linux Certification, 3e

  • Linux+ Guide to Linux Certification, 3e*SummaryThree components are available to commands: standard input, standard output, and standard errorStdin is typically user input taken from the keyboard; Stdout and Stderr are sent to the terminal screenYou can redirect the stdout and stderr of a command to a file using redirection symbols

    Linux+ Guide to Linux Certification, 3e

  • Summary (continued)Use the pipe (|) symbol to redirect stdout from one command to the stdin of anotherMost variables available to the BASH shell are environment variables that are loaded into memory after login from environment filesYou can create your own variables in the BASH shell and export them so that they are available to programs started by the shellLinux+ Guide to Linux Certification, 3e*

    Linux+ Guide to Linux Certification, 3e

  • Summary (continued)The UMASK variable and command aliases are special variables that must be set using a certain commandShell scripts can be used to execute several Linux commandsDecision constructs can be used in shell scripts to execute certain Linux commands based on user input or the results of a certain commandLoop constructs can be used within shell scripts to execute a series of commands repetitivelyLinux+ Guide to Linux Certification, 3e*

    Linux+ Guide to Linux Certification, 3e

    ***********************************************

Recommended

View more >