您正在查看: Shell 分类下的文章

Shell Built-In Commands

9.13 shell Built-In Commands


9.13 shell Built-In Commands


The shell has a number of commands that are built-in to its source code. Because the commands are built-in, the shell doesn't have to locate them on disk, making execution much faster. The help feature provided with bash give you online help for any built-in command. The built-in commands are listed in Table 9.12 on page 481.


Table 9.12. Built-In Commands

Command

What It Does

:

Do-nothing command; returns exit status zero.

. file

The dot command reads and executes command from file.

break [n]

See the looping commands on page 443.

:

Do-nothing command; returns 0 exit status.

.

Executes program in context of current process; same as source.

alias

Lists and creates "nicknames" for existing commands.

bg

Puts a job in the background.

bind

Displays current key and function bindings, or binds keys to a readline function or macro.

break

Breaks out of the innermost loop.

builtin [ sh-builtin [args]]

Runs a shell built-in, passing it args, and returning 0 exit status. Useful if a function and built-in have the same name.

cd [arg]

Changes the directory to home if no arg or to arg.

command command* [arg]

Runs a command even if a function has the same name; i.e., bypasses function lookup.

continue [n]

See the looping commands on page 444.

declare [var]

Displays all variables or declares variables with optional attributes.

dirs

Displays a list of currently remembered directories resulting from pushd.

disown

Removes an active job from the job table.

echo [args]

Displays args terminated with a newline.

enable

Enables and disables shell built-in commands.

eval [args]

Reads args as input to the shell and executes the resulting command(s).

exec command

Runs command in place of this shell.

exit [ n ]

Exits the shell with status n.

export [ var ]

Makes var known to subshells.

fc

History's fix command for editing history commands.

fg

Puts background job into foreground.

getopts

Parses and processes command line options.

hash

Controls the internal hash table for quicker searches for commands.

help [command ]*

Displays helpful info about built-in commands and, if command is specified, detailed help about that built-in command.

history

Displays the history list with line numbers.

jobs

Lists jobs put in the background.

kill [-signal process ]

Sends the signal to the pid number or job number of the process. Type kill -l for a list of signals.

getopts

Used in shell scripts to parse command line and check for legal options.

let

Used for evaluating arithmetic expressions and assigning results of arithmetic calculations to variables.

local

Used in functions to restrict the scope of variables to the function.

logout

Exits the login shell.

popd

Removes entries from the directory stack.

pushd

Adds entries to the directory stack.

pwd

Prints present working directory.

read [ var ]

Reads line from standard input into variable var.

readonly [ var ]

Makes variable var read-only. Cannot be reset.

return [ n ]

Returns from a function where n is the exit value given to the return.

set

Sets options and positional parameters. See Table 9.2 on page 396.

shift [n]

Shifts positional parameters to the left n times.

stop pid

Halts execution of the process number pid.

suspend

Stops execution of the current shell (but not if a login shell).

test

Checks file types and evaluates conditional expressions.

times

Prints accumulated user and system times for processes run from this shell.

trap [ arg ] [ n ]

When shell receives signal n ( 0, 1, 2, or 15), executes arg.

type [ command ]

Prints the type of command; e.g., pwd is a built-in shell command.

typeset

Same as declare. Sets variables and gives them attributes.

ulimit

Diplays and sets process resource limits.

umask [ octal digits ]

Sets user file creation mode mask for owner, group, and others.

unalias

Unsets aliases.

unset [ name ]

Unset value of variable or function.

wait [ pid#n ]

Waits for background process with pid number n and reports termination status.

Bash Options

9.12 Bash Options


9.12 Bash Options


9.12.1 shell Invocation Options

When the shell is started using the bash command, it can take options to modify its behavior. There are two types of options: single-character options and multicharacter options. The single-character options consist of a single leading dash followed by a single character. The multicharacter options consist of two leading dashes and any number of characters. Multicharacter options must appear before single-character options. An interactive login shell normally starts up with -i (start an interactive shell), -s (read from standard input), and -m (enable job control). See Table 9.8 on page 475.

Table 9.8. Bash 2.x Shell Invocation Options

Option

Meaning

-c string

Commands are read from string. Any arguments after string are assigned to positional parameters, starting at $0.

-D

A list of double quoted strings, preceded by a $, are printed to standard output. These strings are subject to language translation when the current locale is not C or POSIX. The -n option is implied; no commands will be executed.

-i

Shell is in the interactive mode. TERM, QUIT, and INTERRUPT are ignored.

-s

Commands are read from standard input and allow the setting of positional parameters.

-r

Starts a restricted shell.

--

Signals the end of options and disables further option processing. Any arguments after -- or - are treated as filenames and arguments.

--dump-strings

Same as -D.

--help

Displays a usage message for a built-in command and exits.

--login

Causes bash to be invoked as a login shell.

--noediting

When bash is running interactively, does not use the Readline library.

--noprofile

When starting up, bash does not read the initialization files: /etc/profile, ~/.bash_profile, ~/.bash_login, or ~/.profile.

--norc

For interactive shells, bash will not read the ~/.bashrc file. Turned on by default, if running shell as sh.

--posix

Changes the behavior of bash to match the POSIX 1003.2 standard, if otherwise it wouldn't.

--quiet

Displays no information at shell startup, the default.

--rcfile file

If bash is interactive, uses this intialization file instead of ~/.bashrc.

--restricted

Starts a restricted shell.

--verbose

Turns on verbose; same as -v.

--version

Displays version information about this bash shell and exit.

Table 9.9. Bash (Versions Prior to 2.x) Shell Invocation Options

-c string

Commands are read from string. Any arguments after string are assigned to positional parameters, starting at $0.

-D

A list of double quoted strings, preceded by a $, are printed to standard output. These strings are subject to language translation when the current locale is not C or POSIX. The -n option is implied; no commands will be executed.

-i

Shell is in the interactive mode. TERM, QUIT, and INTERRUPT are ignored.

-s

Commands are read from standard input and allows the setting of positional parameters.

-r

Starts a restricted shell.

-

Signals the end of options and disables further option processing. Any arguments after -- or - are treated as filenames and arguments.

-login

Causes bash to be invoked as a login shell.

-nobraceexpansion

Curly brace expansion is turned off.

-nolineediting

When bash is running interactively, does not use the Readline library.

-noprofile

When starting up, bash does not read the initialization files: /etc/profile, ~/.bash_profile, ~/.bash_login, or ~/.profile.

-posix

Changes the behavior of bash to match the POSIX standard, if otherwise, it wouldn't.

-quiet

Displays no information at shell startup, the default.

-rcfile file

If bash is interactive, uses this intialization file instead of ~/.bashrc.

-verbose

Turns on verbose; same as -v.

-version

Displays version information about this bash shell and exit.

9.12.2 The set Command and Options

The set command can be used to turn shell options on and off, as well as for handling command line arguments. To turn an option on, the dash (-) is prepended to the option; to turn an option off, the plus sign (+) is prepended to the option. See Table 9.10 on page 477 for a list of set options.

Example 9.78

1 $ set -f

2 $ echo **

3 $ echo ??
??

4 $ set +f

Explanation

  • The f option is turned on, disabling filename expansion.

  • The asterisk is not expanded.

  • The question marks are not expanded.

  • The f is turned off; filename expansion is enabled.

  • Table 9.10. The Built-In set Command Options

    Name of Option

    Shortcut Switch

    What It Does

    allexport

    -a

    Automatically marks new or modified variables for export from the time the option is set, until unset.

    [1]

    braceexpand

    -B

    Enables brace expansion, and is a default setting.

    emacs

    For command line editing, uses the emacs built-in editor, and is a default setting

    errexit

    -e

    If a command returns a nonzero exit status (fails), exits. Not set when reading initialization files.

    []

    histexpand

    -H

    Enables ! and !! when performing history substitution, and is a default setting.

    []

    history

    Enables command line history; on by default.

    ignoreeof

    Disables EOF (Control-D) from exiting a shell; must type exit. Same as setting shell variable, IGNOREEOF=10.

    []

    keyword

    -k

    Places keyword arguments in the environment for a command.

    interactive-comments

    For interactive shells, a leading # is used to comment out any text remaining on the line.

    monitor

    -m

    Allows job control.

    noclobber

    -C

    Protects files from being overwritten when redirection is used.

    noexec

    -n

    Reads commands, but does not execute them. Used to check the syntax of scripts. Not on when running interactively.

    noglob

    -d

    Disables pathname expansion; i.e., turns off wildcards.

    notify

    -b

    Notifies user when background job finishes

    nounset

    -u

    Displays an error when expanding a variable that has not been set.

    []

    onecmd

    -t

    Exits after reading and executing one command.

    physical

    -P

    If set, does not follow symbolic links when typing cd or pwd. The physical directory is used instead.

    posix

    Shell behavior is changed if the default operation doesn't match the POSIX standard.

    privileged

    -p

    When set, the shell does not read the .profile or ENV file and shell functions are not inherited from the environment; automatically set for setuid scripts.

    posix

    Changes the default behavior to POSIX 1003.2

    verbose

    -v

    Turns on the verbose mode for debugging.

    vi

    For command line editing, uses the vi built-in editor.

    xtrace

    -x

    Turns on the echo mode for debugging.

    [1] Asterisk indicates option applies only to versions of bash 2.x.

    9.12.3 The shopt Command and Options

    The shopt (bash 2.x) command can also be used to turn shell options on and off.

    Table 9.11. The shopt Command Options

    Option

    Meaning

    cdable_vars

    If an argument to the cd built-in command is not a directory, it is assumed to be the name of a variable whose value is the directory to change to.

    cdspell

    Corrects minor errors in the spelling of a directory name in a cd command. The errors checked for are transposed characters, a missing character, and a character too many. If a correction is found, the corrected path is printed, and the command proceeds. Only used by interactive shells.

    checkhash

    Bash checks that a command found in the hash table exists before trying to execute it. If a hashed command no longer exists, a normal path search is performed.

    checkwinsize

    Bash checks the window size after each command and, if necessary, updates the values of LINES and COLUMNS.

    cmdhist

    Bash attempts to save all lines of a multiple-line command in the same history entry. This allows easy re-editing of multiline commands.

    dotglob

    Bash includes filenames beginning with a "." in the results of filename expansion.

    execfail

    A noninteractive shell will not exit if it cannot execute the file specified as an argument to the exec built-in command. An interactive shell does not exit if exec fails.

    expand_aliases

    Aliases are expanded. Enabled by default.

    extglob

    The extended pattern matching features (regular expression metacharacters derived from Korn shell for filename expansion) are enabled.

    histappend

    The history list is appended to the file named by the value of the HISTFILE variable when the shell exits, rather than overwriting the file.

    histreedit

    If Readline is being used, a user is given the opportunity to re-edit a failed history substitution.

    histverify

    If set, and Readline is being used, the results of history substitution are not immediately passed to the shell parser. Instead, the resulting line is loaded into the Readline editing buffer, allowing further modification.

    hostcomplete

    If set, and Readline is being used, bash will attempt to perform hostname completion when a word containing an "@" is being completed Enabled by default.

    huponexit

    If set, bash will send SIGHUP (hangup signal) to all jobs when an interactive login shell exits.

    interactive_comments

    Allows a word beginning with "#" to cause that word and all remaining characters on that line to be ignored in an interactive shell. Enabled by default.

    lithist

    If enabled, and the cmdhist option is enabled, multiline commands are saved to the history with embedded newlines rather than using semicolon separators

    where possible.

    mailwarn

    If set, and a file that bash is checking for mail has been accessed since the last time it was checked, the message The mail in mailfile has been read is displayed.

    nocaseglob

    If set, bash matches filenames in a case-insensitive fashion when performing filename expansion.

    nullglob

    If set, bash allows filename patterns which match no files to expand to a null string, rather than themselves.

    promptvars

    If set, prompt strings undergo variable and parameter expansion after being expanded. Enabled by default.

    restricted_shell

    The shell sets this option if it is started in restricted mode. The value may not be changed. This is not reset when the startup files are executed, allowing the startup files to discover whether or not a shell is restricted.

    shift_verbose

    If this is set, the shift built-in prints an error message when the shift count exceeds the number of positional parameters.

    sourcepath

    If set, the source built-in uses the value of PATH to find the directory containing the file supplied as an argument. Enabled by default.

    source

    A synonym for . (a dot)

    The eval Command and Parsing the Command Line

    9.11 The eval Command and Parsing the Command Line


    9.11 The eval Command and Parsing the Command Line


    The eval command evaluates a command line, performs all shell substitutions, and then executes the command line. It is used when normal parsing of the command line is not enough.


    Example 9.76

    1 $ set a b c d
    2 $ echo The last argument is $$#
    3 The last argument is $4

    4 $ eval echo The last argument is $$#
    The last argument is d

    5 $ set -x
    $ eval echo The last argument is $$#

    • eval echo the last argument is '$4'
      ++ echo the last argument is d
      The last argument is d

    Explanation


  • Four positional parameters are set.

  • The desired result is to print the value of the last positional parameter. The $ will print a literal dollar sign. The $# evaluates to 4, the number of positional parameters. After the shell evaluates the $#, it does not parse the line again to get the value of $4.

  • $4 is printed instead of the last argument.

  • After the shell performs variable substitution, the eval command performs the variable substitution and then executes the echo command.

  • Turn on the echoing to watch the order of parsing.


  • Example 9.77

    (From Shutdown Program)
    1 eval /usr/bin/id | /usr/bin/sed 's/[^a-z0-9=].*//'
    2 if [ "${uid:=0}" -ne 0 ]
    then
    3 echo $0: Only root can run $0 exit 2
    fi
  • This is a tricky one. The id program's output is sent to sed to extract the uid part of the string. The output for id is:

    uid=9496(ellie) gid=40 groups=40 uid=0(root) gid=1(daemon) groups=1(daemon)

    The sed regular expression reads: Starting at the beginning of the string, find any character that is not a letter, number, or an equal sign and remove that character and all characters following it. The result is to substitute everything from the first opening parenthesis to the end of the line with nothing. What is left is either: uid=9496 or uid=0

    After eval evaluates the command line, it then executes the resulting command:

    uid=9496 or uid=0

    For example, if the user's id is root, the command executed would be uid=0. This creates a local variable in the shell called uid and assigns zero to it.

  • The value of the uid variable is tested for zero, using command modifiers.

  • If the uid is not zero, the echo command displays the script name ($0) and the message.

  • Debugging

    9.9 Debugging


    9.9 Debugging


    By using the -n option to the bash command, you can check the sytnax of your scripts without really executing any of the commands. If there is a syntax error in the script, the shell will report the error. If there are no errors, nothing is displayed.


    The most commonly used method for debugging scripts is the set command with the -x option, or bash, invoked with the -x option, and the scriptname. See Table 9.7 on page 465 for a list of debugging options. These options allow an execution trace of your script. Each command from your script is displayed after substitution has been performed, and then the command is executed. When a line from your script is displayed, it is preceded with a plus (+) sign.


    With the verbose option turned on, or by invoking the shell with the -v option (bash -v scriptname), each line of the script will be displayed just as it was typed in the script, and then executed.


    Table 9.7. Debugging Options

    Command

    Option

    What It Does

    bash -x scriptname

    Echo option

    Displays each line of script after variable substitutions and before execution

    bash -v scriptname

    Verbose option

    Displays each line of script before execution, just as you typed it

    bash -n scriptname

    Noexec option

    Interprets but does not execute commands

    set -x

    Turns on echo

    Traces execution in a script

    set +x

    Turns off echo

    Turns off tracing


    Example 9.69

    (The Script)
    $ cat todebug
    #!/bin/bash

    Scriptname: todebug

    1 name="Joe Shmoe"
    if [[ $name == "Joe Blow" ]]
    then printf "Hello $name\n"
    fi
    declare -i num=1
    while (( num < 5 ))
    do let num+=1
    done
    printf "The total is %d\n", $num

    (The Output)
    2 bash -x todebug

    • name=Joe Shmoe
    • [[ Joe Shmoe == \J\o\e\ \B\l\o\w ]]
    • declare -i num=1
    • (( num < 5 ))
    • let num+=1
    • (( num < 5 ))
    • let num+=1
    • (( num < 5 ))
    • let num+=1
    • (( num < 5 ))
    • let num+=1
    • (( num < 5 ))
    • printf 'The total is %d\n,' 5
      The total is 5

    Explanation

  • The script is called todebug. You can watch the script run with the -x switch turned on. Each iteration of the loop is displayed and the values of variables are printed as they are set and when they change.

  • Bash is invoked with the -x option. Echoing is turned on. Each line of the script will be displayed to the screen prepended with a plus sign (+). Variable substitution is performed before the line is displayed. The result of the execution of the command appears after the line has been displayed.

  • Positional Parameters and Command Line Arguments

    9.4 Positional Parameters and Command Line Arguments


    9.4 Positional Parameters and Command Line Arguments


    9.4.1 Positional Parameters

    Information can be passed into a script via the command line. Each word (separated by white space) following the script name is called an argument.

    Command line arguments can be referenced in scripts with positional parameters; for example, $1 for the first argument, $2 for the second argument, $3 for the third argument, and so on. After $9, curly braces are used to keep the number as one number. For example, positional parameter 10 is referenced as ${10}. The $# variable is used to test for the number of parameters, and $* is used to display all of them. Positional parameters can be set or reset with the set command. When the set command is used, any positional parameters previously set are cleared out. See Table 9.2.

    Table 9.2. Positional Parameters

    Positional Parameter

    What It References

    $0

    References the name of the script.

    $#

    Holds the value of the number of positional parameters.

    $

    Lists all of the positional parameters.

    $@

    Means the same as $, except when enclosed in double quotes.

    "$*"

    Expands to a single argument (e.g., "$1 $2 $3").

    "$@"

    Expands to separate arguments (e.g., "$1" "$2" "$3").

    $1 … ${10}

    References individual positional parameters.

    Example 9.11

    (The Script)
    #!/bin/bash#
    Scriptname: greetings2
    echo "This script is called $0."
    1 echo "$0 $1 and $2"
    echo "The number of positional parameters is $#"


    (The Command Line)
    $ chmod +x greetings2
    2 $ greetings2
    This script is called greetings2.
    greetings and
    The number of positional paramters is

    3 $ greetings2 Tommy
    This script is called greetings2.
    greetings Tommy and
    The number of positional parameters is 1

    4 $ greetings2 Tommy Kimberly
    This script is called greetings2.
    greetings Tommy and Kimberly
    The number of positional parameters is 2

    Explanation

  • In the script greetings2, positional parameter $0 references the script name, $1 the first command line agreement, and $2 the second command line agreement.

  • The greetings2 script is executed without any arguments passed. The output illustrates that the script is called greetings2 ($0 in the script) and that $1 and $2 were never assigned anything; therefore, their values are null and nothing is printed.

  • This time, one argument is passed, Tommy. Tommy is assigned to positional parameter 1.

  • Two arguments are entered, Tommy and Kimberly. Tommy is assigned to $1 and Kimberly is assigned to $2.

  • 9.4.2 The set Command and Positional Parameters

    The set command with arguments resets the positional parameters[a] Once reset, the old parameter list is lost. To unset all of the positional parameters, use set --. $0 is always the name of the script.

    [a] Remember, without arguments, the set command displays all the variables that have been set for this shell, local and exported. With options, the set command turns on and off shell control options such as -x and -v.

    Example 9.12

    (The Script)#!/bin/bash## Scriptname: args# Script to test command line arguments
    1 echo The name of this script is $0.
    2 echo The arguments are $.
    3 echo The first argument is $1.
    4 echo The second argument is $2.
    5 echo The number of arguments is $#.
    6 oldargs=$

    7 set Jake Nicky Scott # reset the positional parameters
    8 echo All the positional parameters are $*.
    9 echo The number of postional parameters is $#.

    10 echo "Good-bye for now, $1."
    11 set $(date) # reset the positional parameters
    12 echo The date is $2 $3, $6.
    13 echo "The value of $oldargs is $oldargs."
    14 set $oldargs
    15 echo $1 $2 $3

    (The Output)$ args a b c d
    1 The name of this script is args
    2 The arguments are a b c d.
    3 The first argument is a.
    4 The second argument is b.
    5 The number of arguments is 4.
    8 All the positional parameters are Jake Nicky Scott.
    9 The number of positional parameters is 3.
    10 Good-bye for now, Jake.
    12 The date is Mar 25, 2000.
    13 The value of $oldargs is a b c d.

    Explanatioin

  • The name of the script is stored in the $0 variable.

  • $* represents all of the positional parameters.

  • $1 represents the first positional parameter (command line argument).

  • $2 represents the second positional parameter.

  • $# is the total number of positional parameters (command line arguments).

  • All positional parameters are saved in a variable called oldargs.

  • The set command allows you to reset the positional parameters, clearing out the old list. Now, $1 is Jake, $2 is Nicky, and $3 is Scott.

  • $* represents all of the parameters, Jake, Nicky, and Scott.

  • $# represents the number of parameters, 3.

  • $1 is Jake.

  • After command substitution is performed, i.e., date is executed, the positional parameters are reset to the output of the date command.

  • The new values of $2, $3, and $6 are displayed.

  • The values saved in oldargs are printed.

  • The set command creates positional parameters from the values stored in oldargs.

  • The first three positional parameters are displayed.

  • Example 9.13

    (The Script)#!/bin/bash

    Scriptname: checker

    Script to demonstrate the use of special variable# modifiers and arguments

    1 name=${1:?"requires an argument" }
    echo Hello $name

    (The Command Line)
    2 $ checker checker: 1: requires an argument
    3 $ checker Sue Hello Sue

    Explanation

  • The special variable modifier :? will check whether $1 has a value. If not, the script exits and the message is printed.

  • The program is executed without an argument. $1 is not assigned a value; an error is displayed.

  • The checker program is given a command line argument, Sue. In the script, $1 is assigned Sue. The program continues.

  • How $* and $@ Differ

    The $* and $@ differ only when enclosed in double quotes. When $* is enclosed within double quotes, the parameter list becomes a single string. When $@ is enclosed within double quotes, each of the parameters is quoted; that is, each word is treated as a separate string.

    Example 9.14

    1 $ set 'apple pie' pears peaches
    2 $ for i in $* > do
    > echo $i
    > done
    apple
    pie
    pears
    peaches

    3 $ set 'apple pie' pears peaches
    4 $ for i in "$*"
    > do
    > echo $i
    > done
    apple pie pears peaches

    5 $ set 'apple pie' pears peaches
    6 $ for i in $@
    > do
    > echo $i
    > done
    apple
    pie
    pears
    peaches

    7 $ set 'apple pie' pears peaches
    8 $ for i in "$@" At last!!
    > do
    > echo $i
    > done
    apple
    pie
    pears
    peaches

    Explanation

  • The positional parameters are set.

  • When $* is expanded, the quotes surrounding apple pie are stripped; apple and pie become two separate words. The for loop assigns each of the words, in turn, to the variable i, and then prints the value of i. Each time through the loop, the word on the left is shifted off, and the next word is assigned to the variable i.

  • The positional parameters are set.

  • By enclosing $* in double quotes, the entire parameter list becomes one string, apple pie pears peaches. The entire list is assigned to i as a single word. The loop makes one iteration.

  • The positional parameters are set.

  • Unquoted, $@ and $* behave the same way (see entry 2 of this explanation).

  • The positional parameters are set.

  • By surrounding $@ with double quotes, each of the positional parameters is treated as a quoted string. The list would be apple pie, pears, and peaches. The desired result is finally achieved.