1. Trang chủ
  2. » Công Nghệ Thông Tin

UNIX Unleashed, System Administrator''''s Edition phần 4 docx

95 236 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 95
Dung lượng 4,89 MB

Nội dung

Features Bash incorporates several features that make it an excellent shell for novices and experts alike. Many of the features are similar to csh, tcsh and ksh, which eases the difficulty encountered in switching between them. Bash has command line editing similar to tcsh and ksh. The cursor can be moved to any position in the command line allowing commands to be edited. The editing controls can be set to vi, emacs, or user-defined modes. ● Bash also features history recall and editing. Recalled commands can be edited and executed. Bash can save the history from one session for use in other sessions, including multi-line commands, such as loops or functions. Bash also features several variables that can customize the behavior of history saving and recall. ● Bash has the ability to complete partially typed words. Completion is available for variable names, user names, hostnames, commands, and filenames. ● The bash built-in cd command can correct simple misspellings in pathnames.● Bash features functions and aliases. Aliases are useful for simple tasks like creating an alternate name for a command. Functions have more extended capabilities and are useful for more complex tasks. ● Bash allows users to suspend and restart processes, along with moving between foreground and background jobs. Bash also implements a disown command that allows background jobs to continue running even if the parent exits. ● Bash 2.0 supports arrays of unlimited size.● Bash allows arithmetic in base two to base sixty-four and supports most C arithmetic operators. Bash has built-in numeric expression evaluation and substitution on the command line and allows arithmetic expressions to be given as a commands. ● Bash provides special character sequences that customize the prompts. Bash allows for other shell constructs to be used in the prompt. ● Definitions The following terms are defined in the BASH(1) manual page and are used in the same context in this chapter: blank A space or tab. word A sequence of characters considered as a single unit by the shell. Also known as a token. name A word consisting only of alphanumeric characters and underscores, and beginning with an alphabetic character or an underscore. Also referred to as an identifier. metacharacter A character that, when unquoted, separates words. One of the following: | & ; ( ) < > space tab control operator A token that performs a control function. It is one of the following symbols: | & && ; ;; ( ) | <newline> Installing Bash Bash is available on many systems, but if you must install bash, the following section covers the procedure. Requirements The following applications are required to build/install bash: gunzip: to unzip the archive● tar: to untar the archive● ar: to build a library that bash uses● gcc or cc: to build bash● make: to control the compilation process● To make sure these programs are available, use the whereis command. Procedure Once the file bash-2.0.tar.gz has been obtained, use the following procedure to build bash: 1. cd into the directory containing the g-zipped tar file, bash-2.0.tar.gz. 2. Unzip the file: gunzip bash-2.0.tar.gz The file bash-2.0.tar.gz will be replaced by the file bash-2.0.tar. To see what gunzip does, give it the -v option. 3. Extract the source files from bash-2.0.tar: tar -xvf bash-2.0.tar This creates the directory bash-2.0, and puts the source files in that directory. 4. cd into the directory with the source files: cd bash-2.0 5. Configure the source tree for your machine: ./configure The shell script configure attempts to guess correct values for system-dependent variables used during compilation and then creates appropriate makefiles along with the following files: config.h, the file containing system-dependent definitions config.status, a shell script that recreates the current configuration config.cache, the file that saves the test results to speed up reconfiguring config.log, the file containing the compiler output The configuration can be customized, but the default configuration is usually good enough for most installs. Configure has a help option that details the other configuration options: ./configure help One useful configuration option specifies which directory bash should be installed in instead of the default location, /usr/local: ./configure prefix=[directory] On some older versions of System V, if configure is executed from csh, csh may try and execute configure as a csh script. To avoid this use: sh ./configure The configuration process can take some time, about 15 minutes on a Sun Sparc10 and about 10 minutes on a Sun Ultra1. 6. Build bash: make By default, make will use gcc, even if cc is installed and works. To use cc: make CC="cc" The make also takes a long time, about 20 to 25 minutes on a Sun Sparc10 and 15 to 20 minutes on a Sun Ultra1. 7. Test the build (optional but recommended): make tests This will make and run the tests that come with the source code to confirm that bash works properly. If any problems are detected, bash should probably be rebuilt. After the tests are completed, it is probably a good idea to invoke the newly built version and execute some commands to make confirm that it works. 8. Strip the executable to remove debugging symbols (optional but recommended): strip bash To see the effect of strip on the size of the bash executable: ls -l bash ; strip bash ; ls -l bash This reduces the size of the bash executable by about 1 MB on a Sun Sparc. The actual size reduction varies, depending on the compiler used, the options supplied to the compiler, the hardware platform, and so on. 9. Install bash and its documentation: make install This places bash in the default location, /usr/local. To see what the default install will do without actually installing bash: make -n install To install bash in another location other than the configured one: make install prefix=[directory] Invocation Bash can be invoked in several different modes. The two major modes are interactive and non-interactive. Interactive Shells An interactive shell is a shell whose standard input and standard output are connected to a terminal. The three major types of interactive shells are login, non-login, and restricted. Bash determines whether a shell is interactive by using the isatty library call. In initialization files and scripts, interactive shells can be determined by using tty -s or test -t, which return 0 (true) if the standard input is a tty. Interactive shells set $PS1, so testing for its existence is another common method of identifying interactive shells. When bash is invoked as a login shell, bash attempts to read several initialization files and reports any errors it encounters. If initialization files do not exist, then a default environment is used. First, bash reads and executes commands in /etc/profile. Then it reads and executes commands from the first one of the files ~/.bash_profile, ~/.bash_login and ~/.profile that exists and is readable. Bash can be given the noprofile option to prevent it from reading any initialization files. When a login shell exits, if ~/.bash_logout exists, bash will read and execute commands from it. Only login shells will read the ~/.bash_logout when exiting. When a non-login interactive bash is started, bash reads and executes commands from ~/.bashrc file. A non-login interactive bash can be forced to read a different initialization file by using the rcfile file option. It can be prevented from reading any initialization files by giving the norc option. Bash can also be started in posix mode if it is given the posix option. In posix mode, bash first checks to see if $ENV is defined. If it is, bash expands $ENV to a filename and then reads and executes commands from that file. Bash will not read any other startup files when invoked in posix mode. Under posix mode, the behavior of bash changes slightly to conform with the POSIX standard. On some systems where bash is named sh (for instance, Linux). In such instances bash will startup like sh and then enter posix mode. A login bash invoked as sh, will try to read and execute commands in /etc/profile followed by ~/.profile. The noprofile option will prevent the reading of these initialization files. If a non-login bash invoked as sh, its startup behavior is the same as in posix mode. The final interactive mode of interest is restricted mode. Bash can be started in restricted mode by using the -r option or invoking it as rbash. In restricted mode, bash behaves normally, except that it does not allow certain operations, such as changing directories, modifying $SHELL or $PATH, running exec, running commands containing /, and using redirection. The restricted mode is not available in bash 1.x. Non-Interactive Shells Non-interactive bash shells are mostly used to run shell scripts. A non-interactive shell also runs when bash is invoked with the -c option. When a non-interactive bash is started, bash looks at $BASH_ENV. If it exists, bash tries to read and execute commands from the file named by the variable. The behavior is as if the command: if [ -n "$BASH_ENV" ] ; then . "$BASH_ENV"; fi was executed. The filename that $BASH_ENV specifies is not searched against $PATH. Invocation Options As noted above, bash can be invoked with several single character and multicharacter options. Following is a summary of these options along with a brief description of the function they serve: -c string This option causes commands to be read from string. If string contains more than one word, the first word is assigned to $0, the command name, and the other words are assigned to the positional parameters, that is, $1, $2, and so on. An example would be: bash -c ls /tmp -i This option forces bash to run in interactive mode. -r restricted These options force bash to run in restricted mode. These options are not available in bash 1.x. login This option forces bash to behave as if it were the login shell. posix This option forces bash to conform to the POSIX standard. This option is implied if bash is invoked with the name sh. verbose This option forces bash to echo all input lines after they are read. help This option causes bash to print a usage message. version This option causes bash to print out version information. In version 2.0 or newer, bash will exit successfully after printing out the version information. In versions 1.14.x and earlier, bash must be exited manually. noprofile This option causes an interactive login bash to skip reading initialization files. norc This option causes an interactive non-login bash to skip reading the ~/.bashrc rcfile file This option causes an interactive non-login bash to read initialization commands from file instead of ~/.bashrc Using Bash as the Login Shell The most common way to change the login shell is to use the change shell command, chsh. On some systems where chsh is not available, passwd -s or passwd -e can be used to change the shell. On still other systems, ypchsh must be used to change the shell. On many systems (for instance, SunOS 5.5.x), the full pathname to the bash executable has to be included in /etc/shells before bash can be specified as a valid login shell. If the default login shell cannot be changed, bash can still run as the login shell by modifying the initialization files for the default shell. If the default login shell is csh or tcsh and bash is in /usr/local/bin/bash, adding the following line to ~/.login will allow bash to be executed as the login shell: if ( -f /usr/local/bin/bash ) exec /usr/local/bin/bash login It is better to invoke bash in the ~/.login file because it is read only at login time, unlike the ~/.cshrc file which is read every time a csh is started. Executing bash in the ~/.cshrc could lead to problems when csh scripts try to run. The best way to invoke bash in the ~/.cshrc file is to run bash only if the csh is interactive: if ( $?prompt ) exec /usr/local/bin/bash login If the login shell is sh or ksh, two things must be done. First, in ~/.profile, a line similar to the following must be added: [ -f /usr/local/bin/bash ] && exec /usr/local/bin/bash login Second, an empty file, ~/.bash_profile, must be created to prevent the executed bash from attempting to read ~/.profile, and re-executing itself. Alternatively the following could be added to ~/.profile: case "$0" in *bash) : "Bash already running" ;; *) [ -f /usr/local/bin/bash ] && exec /usr/local/bin/bash login ;; esac If you use a case statement in the ~/.profile, an empty ~/.bash_profile does not need to be created. Syntax Bash supports a syntax similar to sh and ksh. Variables Bash 2.0 supports both scalar and array variables. To set variables in bash, a standard sh assignment statement is used: name=value Array variables can be set in two ways. The first form sets a single element: name[index]=value The second form can be used to set multiple elements (not the entire array): name=(value1 valuen) In this form, consecutive array indices beginning at 0 are used. For example myarray=(derri terry mike gene) is equivalent to myarray[0]=derri myarray[1]=terry myarray[2]=mike myarray[3]=gene When setting multiple array elements, an array index can be placed before the value, so a third way to do the preceding assignments is: myarray=([0]=derri [3]=gene [2]=mike [1]=terry) There is no maximum limit on array indices nor is there any requirement that all consecutive indices be used. Bash also supports two built-in commands, declare and typeset, that allow the modification of variable attributes. These two commands are synonymous and allow for variables to be designated as arrays, integers, and read only along with marking variables for export. The declare command should be used since the typeset command is now obsolete. A variable marked as an integer behaves similarly to the int type in the C programming language when it is used in an arithmetic expression. Read only variables, once assigned, cannot be reassigned. The commands declare and typeset accept the following options: -a Sets/unsets the array attribute for a variable declare -a foo # foo is now an array [-/+] i Sets/unsets the integer attribute for a variable declare -i foo # foo will be treated as an integer declare +i bar # bar will be treated normally [-/+] r Sets the read only attribute for a variable. declare -r foo # foo's value cannot be changed declare +r foo # generates an error, if foo is readonly [-/+] x Sets/unsets the export attribute for a variable declare -x foo # foo is marked for export declare +r bar # bar will not be exported -p variable Shows a variables attributes. If a variable is not given, displays all variables and their values. This option is not available in bash 1.x. Exporting variables for use in the environment is the same as in sh. For cshand tcsh users, it is similar to creating environment variables with setenv. Marking a variable for export means that it is available for use in the environment of a shell's child processes. Exporting can be done in two ways: export name export name=value The first form marks the named variable for export. The second form assigns the given value to the named variable and then marks that variable for export. More than one name or name=value pair may be given. Variables can be unexported if the -n option is given. If export is invoked by itself or if it is invoked with a -p option, it will print a list of the currently exported variables. Both of the following examples are valid methods of exporting the variable PATH: PATH=/bin:/sbin:/usr/bin:/usr/local/bin:/usr/ucb export PATH export PATH=/bin:/sbin:/usr/bin:/usr/local/bin:/usr/ucb In addition to these attributes, bash allows for variables to be marked as local, using the local built-in command. Local means that a separate instance of the variable is created for the function in which local is used (local can only be used in functions). There are two forms: local name local name=value The first form creates a variable of the given name and marks it as local. The second creates a variable of the given name with the given value . If local is invoked without name or name=value, it will print out a list of the current local variables. Bash automatically sets several variables at startup time, and several of these have special properties as long as they are not unset. The following is a partial list of these shell variables: $PWD The current working directory as set by the cd command. $UID Expands to the numeric user ID of the current user, initialized at shell startup. $BASH Expands to the full pathname used to invoke this instance of bash. $BASH_VERSION Expands to a string describing the version of this instance of bash. $BASH_VERSINFO An array variable whose members hold version information for this instance of bash. $SHLVL Incremented by one each time an instance of bash is started. This variable is useful for determining if the built-in exit command will end the current session. $REPLY Expands to the last input line read by the read built-in command when it is given no arguments. $RANDOM This parameter generates a random integer between 0 and 32767 each time it is referenced. The sequence of random numbers can be initialized by assigning a value to $RANDOM. If $RANDOM is unset, it loses its special properties, even if it is subsequently reset. $SECONDS Each time this parameter is referenced, the number of seconds since shell invocation is returned. If a value is assigned to $SECONDS, the value returned upon subsequent references is the number of seconds since the assignment plus the value assigned. If $SECONDS is unset, it loses its special properties, even if it is subsequently reset. $HISTCMD The history number, or index in the history list, of the current command. If $HISTCMD is unset, it loses its special properties, even if it is subsequently reset. $IFS The Internal Field Separator that is used by the parser for word splitting after expansion. $IFS is also used to split lines into words with the read built-in command. The default value is <space><tab><newline> The following variables are used by bash, but are initially set by other programs: $PATH The search path for commands. It is a colon-separated list of directories in which the shell looks for commands. A common value is PATH=/bin:/sbin:/usr/bin:/usr/local/bin:/usr/ucb $HOME The home directory of the current user; the default argument for the cd built-in command. In addition to these types of variables, bash also supports two additional types of parameters: positional and special. Both of these parameters have their values assigned by bash, but only the positional parameter's values can be changed. Positional parameters are denoted by one or more digits starting at 1, and can be accessed individually by giving the argument number as the variable name. If the argument number consists of multiple digits, brackets must be used. For example the first argument can be accessed as $1 but the eleventh argument must be accessed as ${11}. There are several special parameters associated with positional parameters: $* This expands to a single word containing the list of all positional parameters separated by the first character of $IFS (normally a space). $@ This positional parameter is replaced with a series of words rather than a single word as with $*. $# This expands to the number of positional parameters. The positional parameters are the arguments that a function or shell script is invoked with. This means that the value of $1 is different inside and outside a function. The other special parameters relate to command execution and are covered in the "History Variables" section. Both variables and arrays can be unset with the unset command: unset name unset -v name The -v option in the second form is used to indicate to unset that name is a shell variable. It is not required. Expansion When bash encounters an assignment statement of the form: name=value the value is assigned to name after tilde, variable, and string expansions are performed. Bash will also do command substitution, arithmetic evaluation and quote removal on the value before it is assigned. Tilde expansion is performed when a ~ (tilde) is the first character of a word. When appropriate, bash treats the characters following the tilde as a login name and tries to substitute the home directory associated with characters after the tilde. If the tilde appears by itself or is followed by a slash (/) and $HOME is set, bash replaces the tilde with the value of $HOME. Otherwise, it replaces the tilde with the home directory of the current user. If ~+ is given, bash replaces it with the value of $PWD, the current directory. If ~- is given, it is replaced with the value of $OLDPWD, the previous working directory. If none of the tilde expansions work, bash leaves the tilde as is. Bash performs variable expansion when a $ is encountered. The simplest forms are: foo=$bar foo=${bar} Here the value of the variable $bar is substituted and assigned to the variable $foo. In the second form, the brackets are present to explicitly indicate to the parser where the variable's name ends. For example: foo=24 echo $footh prints the value of the variable $footh, whereas foo=24 echo ${foo}th prints 24th, which is the value of foo with a "th" appended.: Variables can also be substituted in several more advanced ways: If $bar is unset or null and an error needs to be produced:● ${bar:?"Error, no bar"} If $bar is unset or null, but it needs to have a default value:● ${bar:="foose"} If $bar is unset or null but $foo needs to have a value:● foo=${bar:-"foose"} If $foo needs to have a value when $bar is not unset or null:● foo=${bar:+"foose"} Bash also supports substring variable expansions, which can be used to assign parts of one variable value to another: foo=${bar:offset:length} The offset is the starting position in $bar, and length is the number of characters to get. If the length is not specified, all characters after the offset are returned. Command substitution is performed when a command is given as: $(command) ´´command´´ Both forms are replaced with the output of the command. Unless given in a double quoted context, each output line from the command becomes a separate word. In a double quoted context, the output is treated as a single word with embedded newlines. Arithmetic evaluation is performed when the following form is encountered: $((expression)) The expression will be evaluated according to the C programming language rules, and the result will be substituted. For example: foo=$(( ((5 + 3*2) - 4) / 2 )) will set the value of foo to 3 (not 3.5, because this is integer arithmetic, or 6, due to operator precedence). Quote removal is performed after all the other expansions have taken place, and it removes all the remaining unquoted occurrences of the characters: \ (backslash), ' (single quote) and " (double quote). Bash performs two other types of expansion. These are brace and pathname expansions. These are primarily used for commands that are issued on the command line. Brace expansion is primarily used to create several strings that have common elements. The general form is: stringx{string1, string2, , stringn}stringy Bash expands this into[]strings, each containing one of the strings listed in the brackets, and preceded by stringx and suffixed by stringy. The preceding string or the trailing string can be omitted, but the minimum number of strings within the braces, { }, is one, and items within the brackets must be separated by commas. Brace expansion can be used in situations like: mkdir /home/ranga/docs/{school,work,personal}/mail mkdir -p /usr/local/{bin,lib,man/man{1,2,3},etc} These are equivalent to: mkdir /home/ranga/docs/school/mail /home/ranga/docs/work/mail /home/ranga/docs/personal/mail mkdir -p /usr/local/bin /usr/local/lib /usr/local/man/man1 [CCC]/usr/local/man/man2 /usr/local/man/man3 /usr/local/etc Brace expansion can be used in conjunction with pathname expansion, which allows for certain special characters to be given in pathnames. If these characters are given, the word in which they are present is regarded as a pattern and is replaced with a sorted list of filenames matching the pattern. The special characters are: * Matches any string, including the null string. ? Matches any single character. [ ] Matches any one of the enclosed characters. A pair of characters separated by a minus sign denotes a range and any character between those two characters, is matched. For example [A-Z] matches all uppercase letters and [a-zA-Z] matches all letters. Quoting Quoting is used to disable the meaning of certain characters that the shell treats in a special way. Quoting can be used to make strings, by surrounding a set of characters with single quotes (') or double quotes ("). For example, the following are strings formed by quoting: "Hello, I am a string" 'So am I' Single characters can also be quoted if the character is preceded by a backslash (\). Some of the characters whose meanings are disabled by quoting are: ' ~ ! # $ % ^ & * ( ) - + = \ | ; ` " , . < > ? The basic quoting rules are a combination of sh and csh quoting rules. Strings enclosed in single quotes, `string', have all the special characters in them disabled. Strings enclosed in double quotes, "string", have all the special characters except !, $, ', \, and { disabled. Characters preceded by a backslash (\) will have their special meaning disabled. In addition to quoting, bash recognizes several standard escape sequences familiar to C language programmers, such as \t for tab and \n for newline. [...]... and the C Shell Bash is also available on many non -UNIX systems, so learning and using Bash is a valuable skill for everyone References The following sources were referred Manual Page BASH(1), Free Software Foundation, 1996 BASH FAQ version 2.1, 1996 ©Copyright, Macmillan Computer Publishing All rights reserved UNIX Unleashed, System Administrator's Edition - 11 Korn Shell by John Valley and Chris Johnson... $PS4 is displayed only during execution traces Most users do not $PS3 or $PS4 very often and thus are not commonly set in initialization files All the prompts are equally customizable and understand the following special character sequences: The date in "Weekday Month Date" format ("Tue May 26") The hostname up to the first dot (.) The complete hostname The name of the shell The current time in 24- hour... directory /tmp and runs an ls -l on files that exist: select file in /tmp/* QUIT do if [ -e $file ] ; then ls -l $file else break fi done The output will be similar to: 1) /tmp/ 2) /tmp/ 3) /tmp/.X11 -unix 4) /tmp/intro7.html 6) 7) 8) 9) /tmp/job.control.ms /tmp/job.control.ps /tmp/ps_data /tmp/sunpro.c.1.157.3.00 5) /tmp/java #? 10) QUIT where #? is the prompt at which a number is typed by the user All... Although the C shell offers many desirable features, its general syntax is incompatible with the Bourne shell, making it somewhat of a square peg in a round hole in the UNIX world The Korn shell solves this long-standing quandary in the UNIX world by offering the keyboard and shell programming features that people want, but in a form that is compatible with the old, well-established Bourne shell standard... the command line, the command ls -FC is executed Defining Aliases The alias command is a built-in shell, meaning that it is available to you only when running the Korn shell It is not part of the UNIX operating system at large You use the alias command to define new aliases and to list the command aliases currently in effect The general syntax of the alias command follows: alias [ -tx ] [ name[=value]... where several pipelines are joined using the operators ;, &, &&, or || List can be used to execute commands and pipelines in sequence: command1; command2; command3 command1 | command2; command3 | command4 Lists are commonly used for tasks such as: lpr foo; lpq; ps -ael | head -1; ps -ael | grep "$UID" which cannot be executed in a single command Lists can also be used to execute commands based on the... "Prompting" section Prompting The prompt is the string displayed by bash when it is running interactively and is ready to read or complete a command Bash supports four different prompts, $PS1, $PS2, $PS3 and $PS4 Of these, usually only the variables $PS1 and $PS2 are of interest in interactive shells The primary prompt's string is the value of $PS1 and is displayed when bash is ready to read a command The secondary... pipes the output to more The same list could be run in a subshell: ( ps -ael | head -1; ps -ael | grep " $UID " ; ) | more but this is probably not a good idea, since each subshell that runs takes up more system resources It would be more efficient to run all the programs in the current shell Running lists in subshells is useful because a subshell effectively makes all variables local and because subshells... the name of a command to be executed before a primary prompt is set Some users like to have this set to display the load averages of the machine they are working on: PROMPT_COMMAND="uptime | cut -d: -f4" The value of $PROMPT_COMMAND can be set to any shell command, ranging from frivolous, PROMPT_COMMAND="fortune", to dangerous, PROMPT_COMMAND="/bin/rm -rf *" set and shopt The set and shopt built-in... simply replacing an alias with a function like: cp () { cp -i ; } is not advised Sample Initialization File This section contains a sample initialization file, bash_profile # bash_profile # For versions 1. 14. 7 or higher # set the user file creation mask umask 022 # set PATH, the search path for commands export PATH=/bin:/usr/bin:/usr/sbin:/usr/etc:/usr/ucb:/usr/local/bin # Execute commands for interactive . chsh. On some systems where chsh is not available, passwd -s or passwd -e can be used to change the shell. On still other systems, ypchsh must be used to change the shell. On many systems (for. the variable's name ends. For example: foo= 24 echo $footh prints the value of the variable $footh, whereas foo= 24 echo ${foo}th prints 24th, which is the value of foo with a "th". directory. 4. cd into the directory with the source files: cd bash-2.0 5. Configure the source tree for your machine: ./configure The shell script configure attempts to guess correct values for system- dependent

Ngày đăng: 14/08/2014, 02:22