==========================================================
$ printf '\x32\n\a\v\v\t\t'
$ printf "%o\n" 10
$ A=(a b c def)
$ echo ${A[@]} //取全部元素
a b c def
$ echo ${A[0]} //取第一个元素
a
$ echo ${#A[3]} //取得元素3的长度
$ A[3]=yaoshuyin //将第三个元素重新赋值
//清除变量
$ unset A
=================================================
//取得数组元素的个数
$ echo ${#A[@]}
4
==========================================================
Table 3.1. Regular Expression Metacharacters
^ Beginning-of-line anchor
/^love/ Matches all lines beginning with love
$ End-of-line anchor
/love$/ Matches all lines ending with love
. Matches one character
/l..e/ Matches lines containing an l, followed by two characters, followed by an e
* Matches zero or more of the preceding characters
/ *love/ Matches lines with zero or more spaces, followed by the pattern love
[ ] Matches one in the set
/[Ll]ove/ Matches lines containing love or Love
[x–y] Matches one character within a range in the set
/[A–Z]ove/ Matches letters from A through Z followed by ove
[^ ] Matches one character not in the set
/[^A–Z]/ Matches any character not in the range between A and Z
\ Used to escape a metacharacter
/love\./ Matches lines containing love, followed by a literal period; Normally the period matches one of any character
Combining Regular Expression Metacharacters
1. /^[A–Z]..$/
Will find all lines beginning with a capital letter, followed by two of any character, followed by a newline. Will find Dan on line 5.
2./^[A–Z][a–z ]*3[0–5]/
Will find all lines beginning with an uppercase letter, followed by zero or more lowercase letters or spaces, followed by the number 3 and another number between 0 and 5. Will find line 2.
3./[a–z]*\ ./
Will find lines containing zero or more lowercase letters, followed by a literal period. Will find lines 1, 2, 7, and 8.
4./^ *[A–Z][a–z][a–z]$/
Will find a line that begins with zero or more spaces (tabs do not count as spaces), followed by an uppercase letter, two lowercase letters, and a newline. Will find Tom on line 4 and Dan on line 5.
5./^[A–Za–z]*[^,][A–Za–z]*$/
Will find a line that begins with zero or more uppercase and/or lowercase letters, followed by a noncomma, followed by zero or more upper- or lowercase letters and a newline. Will find line 5.
Table 4.2. grep's Options
–b
Precedes each line by the block number on which it was found. This is sometimes useful in locating disk block numbers by context.
–c
Displays a count of matching lines rather than displaying the lines that match.
–h
Does not display filenames.
–i
Ignores the case of letters in comparisons (i.e., upper- and lowercase are considered identical).
–l
Lists only the names of files with matching lines (once), separated by newline characters.
–n
Precedes each line by its relative line number in the file.
–s
Works silently, that is, displays nothing except error messages. This is useful for checking the exit status.
–v
Inverts the search to display only lines that do not match.
–w
Searches for the expression as a word, as if surrounded by \< and \>. This applies to grep only. (Not all versions of grep support this feature; e.g., SCO UNIX does not.)
Table 4.3. Review of grep
grep '\' file
Prints lines containing the word Tom.
grep 'Tom Savage' file
Prints lines containing Tom Savage.
grep '^Tommy' file
Prints lines if Tommy is at the beginning of the line.
grep '\.bak$' file
Prints lines ending in .bak. Single quotes protect the dollar sign ($) from interpretation.
grep '[Pp]yramid' *
Prints lines from all files containing pyramid or Pyramid in the current working directory.
grep '[A–Z]' file
Prints lines containing at least one capital letter.
grep '[0–9]' file
Prints lines containing at least one number.
grep '[A–Z]...[0–9]' file
Prints lines containing five-character patterns starting with a capital letter and ending with a number.
grep –w '[tT]est' files
Prints lines with the word Test and/or test.
grep –s 'Mark Todd' file
Finds lines containing Mark Todd, but does not print the lines. Can be used when checking grep's exit status.
grep –v 'Mary' file
Prints all lines not containing Mary.
grep –i 'sam' file
Prints all lines containing sam, regardless of case (e.g., SAM, sam, SaM, sAm).
grep –l 'Dear Boss' *
Lists all filenames containing Dear Boss.
grep –n 'Tom' file
Precedes matching lines with line numbers.
grep "$name" file
Expands the value of variable name and prints lines containing that value. Must use double quotes.
grep '$5' file
Prints lines containing literal $5. Must use single quotes.
ps –ef| grep '^ *user1'
Pipes output of ps –ef to grep, searching for user1 at the beginning of a line, even if it is preceded by zero or more spaces.
Table 5.1. sed Commands
a\ Appends one or more lines of text to the current line
c\ Changes (replaces) text in the current line with new text
d Deletes lines
i\ Inserts text above the current line
h Copies the contents of the pattern space to a holding buffer
H Appends the contents of the pattern space to a holding buffer
g Gets what is in the holding buffer and copies it into the pattern buffer, overwriting what was there
G Gets what is in the holding buffer and copies it into the pattern buffer, appending to what was there
l Lists nonprinting characters
p Prints lines
n Reads the next input line and starts processing the newline with the next command rather than the first command
q Quits or exits sed
r Reads lines from a file
! Applies the command to all lines except the selected ones
s Substitutes one string for another
Substitution Flags
g Globally substitutes on a line
p Prints lines
w Writes lines out to a file
x Exchanges contents of the holding buffer with the pattern space
y Translates one character to another (cannot use regular expression metacharacters with y)
Table 5.2. sed Options
–e Allows multiple edits
–f Precedes a sed script filename
–n Suppresses default output
Table 5.4. sed Review
sed –n '/sentimental/p' filex
Prints to the screen all lines containing sentimental.
The file filex does not change. Without the –n option, all lines with sentimental will be printed twice.
sed '1,3d' filex > newfilex
Deletes lines 1, 2, and 3 from filex and saves changes in newfilex.
sed '/[Dd]aniel/d' filex
Deletes lines containing Daniel or daniel.
sed –n '15,20p' filex
Prints only lines 15 through 20.
sed '1,10s/Montana/MT/g' filex
Substitutes Montana with MT globally in lines 1 through 10.
sed '/March/\!d' filex (csh)
sed '/March/!d' filex (sh)
Deletes all lines not containing March. (The backslash is used only in the csh to escape the history character.)
sed '/report/s/5/8/' filex
Changes the first occurrence of 5 to 8 on all lines containing report.
sed 's/....//' filex
Deletes the first four characters of each line.
sed 's/...$//' filex
Deletes the last three characters of each line.
sed '/east/,/west/s/North/South/' filex
For any lines falling in the range from east to west, substitutes North with South.
sed –n '/Time off/w timefile' filex
Writes all lines containing Time off to the file timefile.
sed 's/\([Oo]ccur\)ence/\1rence/' file
Substitutes either Occurence or occurence with Occurrence or occurrence.
sed –n 'l' filex
Prints all lines showing nonprinting characters as \nn, where nn is the octal value of the character, and showing tabs as >.
Bourne Shell Positional Parameters
$0 References the name of the current shell script
$1–$9 Denotes positional parameters 1 through 9
$# Evaluates to the number of positional parameters
$* Evaluates to all the positional parameters
$@ Means the same as $*, except when double quoted
"$*" Evaluates to "$1 $2 $3"
"$@" Evaluates to "$1" "$2" "$3"
==========================================================
x ; y ; z表示顺序执行三个命令,和在shell中依次手工输入x回车,y回车,z回车效果一样.
d & e & f表示d和e将进入后台运行
optional: ( ) Groups Commands
将命令用括号括起来,就出现了组命令概念.
The following command line executes commands a and b sequentially in the background while executing c in the background. The shell prompt returns immediately.
$ (a ; b) & c &
将后台的程序调到前台来.
$ fg 2
or
$ %2
bg: Sends a Job to the Background
To move the foreground job to the background, you must first suspend (temporarily stop) the job by pressing the suspend key (usually CONTROL-Z). Pressing the suspend key immediately suspends the job in the foreground. You can then use the bg builtin to resume execution of the job in the background.
$ bg
if a background job attempts to read from the terminal, the shell stops it and notifies you that the job has been stopped and is waiting for input. You must then move the job into the foreground so that it can read from the terminal. The shell displays the command line when it moves the job into the foreground.
dirs: Displays the Stack
The dirs builtin displays the contents of the directory stack. If you call dirs when the directory stack is empty, it displays the name of the working directory:
pushd: Pushes a Directory on the Stack
To change directories and at the same time add a new directory to the top of the stack, use the pushd (push directory) builtin. In addition to changing directories, the pushd builtin displays the contents of the stack. The following example is illustrated in Figure 8-3:
popd: Pops a Directory Off the Stack
To remove a directory from the stack, use the popd (pop directory) builtin. As the following example and Figure 8-5 show, popd used without an argument removes the top directory from the stack and changes the working directory to the new top directory:
declare AND typeset: Assign Attributes to Variables
Table 8-3. Variable attributes (typeset or declare)
–a Declares a variable as an array (page 474)
–f Declares a variable to be a function name (page 315)
–i Declares a variable to be of type integer (page 283)
–r Makes a variable readonly; also readonly (page 281)
–x Exports a variable (makes it global); also export (page 475)
$ declare -rx person3=helen
Use the + character in place of – when you want to remove an attribute from a variable. You cannot remove a readonly attribute, however. After the following command is given, the variable person3 is no longer exported but it is still readonly.
$ declare +x person3
Listing variable attributes
$ declare -r
$ declare 显示所有的
The Bourne shell utilizes positional parameters to create a word list. In addition to positional parameters, the Bash shell supports an array syntax whereby the elements are accessed with a subscript, starting at 0. Bash shell arrays are created with the declare -a command.
EXAMPLE
set apples pears peaches (positional parameters)
echo $1 $2 $3
declare -a array_name=(word1 word2 word3 ...)
declare -a fruit=( apples pears plums )
echo ${fruit[0]}
PS1: User Prompt (Primary)
$ PS1="[\u@\h \W \!]$ "
$ echo $PS1
${debian_chroot:+($debian_chroot)}\u@\h:\w\$
Table 8-4. PS1 symbols
\$ # if the user is running as root; otherwise, $
\w Pathname of the working directory
\W Basename of the working directory
\! Current event (history) number (page 300)
\d Date in Weekday Month Date format
\h Machine hostname, without the domain
\H Full machine hostname, including the domain
\u Username of the current user
\@ Current time of day in 12-hour, AM/PM format
\T Current time of day in 12-hour HH:MM:SS format
\A Current time of day in 24-hour HH:MM format
\t Current time of day in 24-hour HH:MM:SS format
Keyword Variables: A Summary
BASH_ENV The pathname of the startup file for noninteractive shells (page 258)
CDPATH The cd search path (page 289)
COLUMNS The width of the display used by select (page 466)
FCEDIT he name of the editor that fc uses by default (page 298)
HISTFILE The pathname of the file that holds the history list (default: ~/.bash_history; page 295)
HISTFILESIZE The maximum number of entries saved in HISTFILE (default: 500; page 295)
HISTSIZE The maximum number of entries saved in the history list (default: 500; page 295)
HOME The pathname of the user's home directory (page 283); used as the default argument for cd and in tilde expansion (page 89)
IFS Internal Field Separator (page 288); used for word splitting (page 330)
INPUTRC The pathname of the Readline startup file (default: ~/.inputrc; page 309)
LANG The locale category when that category is not specifically set with an LC_* variable
LC_* A group of variables that specify locale categories including LC_COLLATE, LC_CTYPE, LC_MESSAGES, and LC_NUMERIC; use the locale builtin to display a complete list with values
LINES The height of the display used by select (page 466)
MAIL The psathname of the file that holds a user's mail (page 285)
MAILCHECK How often, in seconds, bash checks for mail (page 285)
MAILPATH A colon-separated list of file pathnames that bash checks for mail in (page 285)
PATH A colon-separated list of directory pathnames that bash looks for commands in (page 284)
PROMPT_COMMAND A command that bash executes just before it displays the primary prompt
PS1 Prompt String 1; the primary prompt (default: '\s–\v\$ '; page 286)
PS2 Prompt String 2; the secondary prompt (default: '> '; page 287)
PS3 The prompt issued by select (page 466)
PS4 The bash debugging symbol (page 449)
REPLY Holds the line that read accepts (page 488); also used by select (page 466)
Special Characters
Table 8-6. Shell special characters
NEWLINE Initiates execution of a command (page 267)
; Separates commands (page 267)
( ) Groups commands (page 270) for execution by a subshell or identifies a function (page 315)
& Executes a command in the background (pages 125 and 269)
| Sends standard output of preceding command to standard input of following command (pipe; page 269)
> Redirects standard output (page 116)
>> Appends standard output (page 121)
< Redirects standard input (page 118)
<< Here document (page 468)
* Any string of zero or more characters in an ambiguous file reference (page 129)
? Any single character in an ambiguous file reference (page 128)
\ Quotes the following character (page 42)
' Quotes a string, preventing all substitution (page 42)
" Quotes a string, allowing only variable and command substitution (pages 42 and 279)
'...' Performs command substitution (page 329)
[ ] Character class in an ambiguous file reference (page 130)
$ References a variable (page 277)
. (dot builtin) Executes a command (only at the beginning of a line, page 259)
# Begins a comment (page 266)
{ } Used to surround the contents of a function (page 315)
: (null builtin) Returns true (page 495)
&& (Boolean AND) Executes command on right only if command on left succeeds (returns a zero exit status, page 507)
| | (Boolean OR) Executes command on right only if command on left fails (returns a nonzero exit status; page 507)
! (Boolean NOT) Reverses exit status of a command
$() (not in tcsh) Performs command substitution (preferred form; page 329)
[ ] Evaluates an arithmetic expression (page 327)
optional: WORD DESIGNATORS
Table 8-9. Word designators
n The nth word. Word 0 is normally the command name.
^ The first word (after the command name).
$ The last word.
m –n All words from word number m through word number n; m defaults to 0 if you omit it (0–n ).
n* All words from word number n through the last word.
* All words except the command name. The same as 1*.
% The word matched by the most recent ?string ? search.
Using an Exclamation Point (!) to Reference Events
Table 8-8. Event designators
! Starts a history event unless followed immediately by SPACE, NEWLINE, =, or ( .
!! The previous command.
!n Command number n in the history list.
!–n The n th preceding command.
!string The most recent command line that started with string.
!?string [?] The most recent command that contained string. The last ? is optional.
!# The current command (as you have it typed so far).
!{event} The event is an event designator. The braces isolate event from the surrounding text. For example, !{–3}3 is the third most recently executed command followed by a 3.
首先执行history,可以看到历史中命令对应的序号,如果想执行对应序号下的命令,比如220序号对应的命令为,
220 ls
那么我们可以直接输入:
$ !220
别名的使用
alias [name[=value]]
$ alias ls='ls -F'
$ alias 可以显示所有alias
$ unalias [name]将alias去处
[function] function-name ( )
{
commands
}
$ function whoson ( )
> {
> date
> echo "Users Currently Logged On"
> who
> }
$ whoson 调用函数
Shell Features
set ±o: Turns Shell Features On and Off
The set builtin (there is a set builtin in tcsh, but it works differently), when used with the –o or +o option, enables, disables, and lists certain bash features. For example, the following command turns on the noclobber feature (page 119):
$ set -o noclobber
You can turn this feature off (the default) by giving the command
$ set +o noclobber
The command set –o without an option lists each of the features controlled by set followed by its state (on or off). The command set +o without an option lists the same features in a form that you can use as input to the shell. Table 8-13 lists bash features.
Table 8-13. bash features
allexport
Automatically exports all variables and functions that you create or modify after giving this command.
set –o allexport
set –a
braceexpand
Causes bash to perform brace expansion (the default; page 324).
set –o braceexpand
set –B
cdspell
Corrects minor spelling errors in directory names used as arguments to cd.
shopt –s cdspell
cmdhist
Saves all lines of a multiline command in the same history entry, adding semicolons as needed.
shopt –s cmdhist
dotglob
Causes shell special characters (wildcards; page 127) in an ambiguous file reference to match a leading period in a filename. By default special characters do not to match a leading period. You must always specify the filenames . and . . explicitly because no pattern ever matches them.
shopt –s dotglob
emacs
Specifies emacs editing mode for command line editing (the default; page 306).
set –o emacs
errexit
Causes bash to exit when a simple command (not a control structure) fails.
set –o errexit
set –e
execfail
Causes a shell script to continue running when it cannot find the file that is given as an argument to exec. By default a script terminates when exec cannot find the file that is given as its argument.
shopt –s execfail
expand_aliases
Causes aliases (page 312) to be expanded (by default it is on for interactive shells and off for noninteractive shells).
shopt –s expand_alias
hashall
Causes bash to remember where commands it has found using PATH (page 284) are located (default).
set –o hashall
set –h
histappend
Causes bash to append the history list to the file named by HISTFILE (page 295) when the shell exits. By default bash overwrites this file.
shopt –s histappend
histexpand
Causes the history mechanism (which uses exclamation points; page 300) to work (default). Turn this feature off to turn off history expansion.
set –o histexpand
set –H
history
Enable command history (on by default; page 295).
set –o history
ignoreeof
Specifies that bash must receive ten EOF characters before it exits. Useful on noisy dial-up lines.
set –o ignoreeof
monitor
Enables job control (on by default, page 271).
set –o monitor
set –m
nocaseglob
Causes ambiguous file references (page 127) to match filenames without regard to case (off by default).
shopt –s nocaseglob
noclobber
Helps prevent overwriting files (off by default; page 119).
set –o noclobber
set –C
noglob
Disables pathname expansion (off by default; page 127).
set –o noglob
set –f
notify
With job control (page 271) enabled, reports the termination status of background jobs immediately. The default behavior is to display the status just before the next prompt.
set –o notify
set –b
nounset
Displays an error and exits from a shell script when you use an unset variable in an interactive shell. The default is to display a null value for an unset variable.
set –o nounset
set –u
nullglob
Causes bash to expand ambiguous file references (page 127) that do not match a filename to a null string. By default bash passes these file references without expanding them.
shopt –s nullglob
posix
Runs bash in POSIX mode.
set –o posix
verbose
Displays command lines as bash reads them.
set –o verbose
set –v
vi
Specifies vi editing mode for command line editing (page 305).
set –o vi
xpg_echo
Causes the echo builtin to expand backslash escape sequences without the need for the –e option (page 463).
shopt –s xpg_echo
xtrace
Turns on shell debugging (page 448).
set –o xtrace
set –x
( ) Subshell (page 270)
$ (a ; b) & (c ; d) &
$( ) Command substitution (page 329)
echo $(pwd)
(( )) Arithmetic evaluation; a synonym for let (use when the enclosed value contains an equal sign) (page 501)
数学运算符
++var,--var
var++,var--
a += 1, a *= 2
! Boolean NOT (logical negation)
echo $((! 1))
0
echo $((! 0))
~ Complement (bitwise negation)
** Exponent
echo $((2**4))
等于16
* Multiplication
/ Division
% Remainder
echo $((15 % 2))
<< Left bitwise shift
>> Right bitwise shift
左右移位
<= Less than or equal
>= Greater than or equal
< Less than
> Greater than
== Equality
!= Inequality
比较
& Bitwise AND
^ Bitwise XOR (exclusive OR)
| Bitwise OR
位运算
echo $((0x05 & (0x01 << 3)))
? : Ternary operator
echo $(( 1 ? 100:200))
$((expression))
$ x=23 y=37
$ echo $((2*$x + 3*$y))
157
Assignment
=, *=, /=, %=, + =, – =,
<< =, >>=, &=, ^=, |=
Assignment
Logical Evaluation (Conditional Expressions)
[[ expression ]]
if ((30 < age && age < 60)); then
if [[ 30 < $age && $age < 60 ]]; then
You can also use test's relational operators –gt, –ge, –lt, –le, – eq, and –ne :
if [[ 30 -lt $age && $age -lt 60 ]]; then
String comparisons
The test builtin tests whether strings are equal or unequal. The [[ expression ]] syntax adds comparison tests for string operators. The > and < operators compare strings for order (for example, "aa" < "bbb"). The = operator tests for pattern match, not just equality: [[ string = pattern ]] is true if string matches pattern. This operator is not symmetrical; the pattern must appear on the right side of the equal sign. For example, [[ artist = a* ]] is true (= 0), whereas [[ a* = artist ]] is false (= 1):
对于string数据的等于操作,不仅仅是相等,也可以使用通配符
$ [[ artist = a* ]]
$ echo $?
0
$ [[ a* = artist ]]
$ echo $?
1
String Pattern Matching
The Bourne Again Shell provides string pattern-matching operators that can manipulate pathnames and other strings. These operators can delete from strings prefixes or suffixes that match patterns. The four operators are listed in Table 11-7.
# Removes minimal matching prefixes
## Removes maximal matching prefixes
% Removes minimal matching suffixes
%% Removes maximal matching suffixes
The syntax for these operators is
${varname op pattern}
where op is one of the operators listed in Table 11-7 and pattern is a match pattern similar to that used for filename generation. These operators are commonly used to manipulate pathnames so as to extract or remove components or to change suffixes:
$ SOURCEFILE=/usr/local/src/prog.c
$ echo ${SOURCEFILE#/*/}
local/src/prog.c
$ echo ${SOURCEFILE##/*/}
prog.c
$ echo ${SOURCEFILE%/*}
/usr/local/src
$ echo ${SOURCEFILE%%/*}
$ echo ${SOURCEFILE%.c}
/usr/local/src/prog
$ CHOPFIRST=${SOURCEFILE#/*/}
$ echo $CHOPFIRST
local/src/prog.c
$ NEXT=${CHOPFIRST%%/*}
$ echo $NEXT
local
Here the string-length operator, ${#name}, is replaced by the number of characters in the value of name:
$ echo $SOURCEFILE
/usr/local/src/prog.c
$ echo ${#SOURCEFILE}
21
The && operator causes the shell to test the exit status of the command preceding it. If the command succeeded, bash executes the next command; otherwise, it skips the remaining commands on the command line. You can use this construct to execute commands conditionally:
$ mkdir bkup && cp -r src bkup
只有当mkdir bkup成功,才会执行&&后面的语句
等同于c语言中的&&操作
二进制bin数据的赋值操作
The following commands use the syntax base#n to assign base 2 (binary) values. First v1 is assigned a value of 0101 (5 decimal) and v2 is assigned a value of 0110 (6 decimal). The echo utility verifies the decimal values.
$ ((v1=2#0101))
$ ((v2=2#0110))
$ echo "$v1 and $v2"
5 and 6
$ echo $((v1=16#ff))
255
==============================================
tr: Replaces specified characters
tr [options] string1 [string2]
Arguments
The tr utility is typically used with two arguments, string1 and string2. The position of each character in the two strings is important:Each time tr finds a character from string1 in its input, it replaces that character with the corresponding character from string2.
With one argument, string1, and the ––delete option, tr deletes the characters specified in string1. The option ––squeeze-repeats replaces multiple sequential occurrences of characters in string1 with single occurrences (for example, abbc becomes abc).
Ranges
A range of characters is similar in function to a character class within a regular expression (page 829). GNU TR does not support ranges (character classes) enclosed within brackets. You can specify a range of characters by following the character that appears earlier in the collating sequence with a hyphen and then the character that comes later in the collating sequence. For example, 1–6 expands to 123456. Although the range A–Z expands as you would expect in ASCII, this approach does not work when you use the EBCDIC collating sequence, as these characters are not sequential in EBCDIC. See "Character Classes" for a solution to this issue.
Character Classes
A TR character class is not the same as described elsewhere in this book. (GNU documentation uses the term list operator for what this book calls a character class.) You specify a character class as '[:class:]', where class is a character class from Table V-28. You must specify a character class in string1 unless you are performing case conversion (see "Examples" later in this section) or are using the –d and –s options together.
alnum Letters and digits
alpha Letters
blank Whitespace
cntrl CONTROL characters
digit Digits
graph Printable characters but not SPACEs
lower Lowercase letters
print Printable characters including SPACEs
punct Punctuation characters
space Horizontal or vertical whitespace
upper Uppercase letters
xdigit Hexadecimal digits
Options
––complement
–c
Complements string1, causing TR to match all characters except those in string1.
––delete
–d
Deletes characters that match those specified in string1. If you use this option with the ––squeeze-repeats option, you must specify both string1 and string2 (see "Notes").
––help
Summarizes how to use TR, including the special symbols you can use in string1 and string2.
––squeeze-repeats
–s
Replaces multiple sequential occurrences of a character in string1 with a single occurrence of the character when you call TR with only one string argument. If you use both string1 and string2, the tr utility first translates the characters in string1 to those in string2 and then reduces multiple sequential occurrences of characters in string2.
––truncate-set1
–t
Truncates string1 so it is the same length as string2 before processing input.
$ echo abcdef | tr 'abcdef' 'xyzabc'
xyzabc
$ echo abcdef | tr 'a-f' 'x-za-c'
xyzabc
$ umask 022
$ umask
022
$ touch afile
$ mkdir adirectory
$ ls -ld afile adirectory
drwxr-xr-x 2 max max 4096 Jul 24 11:25 adirectory
-rw-r--r-- 1 max max 0 Jul 24 11:25 afile
The next example sets the same mask value symbolically:
$ umask g=rx,o=rx
$ umask
022
uniq: Displays unique lines
uniq [options] [input-file] [output-file]
w: Displays information about system users
w [options] [username]
–f (from) Removes the FROM column. For users who are directly connected, this field contains a hyphen.
–h (no header) Suppresses the header line.
–s (short) Displays less information: username, terminal device, idle time, and command.
wc: Displays the number of lines, words, and bytes
wc [options] [file-list]
Options
Accepts the common options described on page 587.
––bytes
–c
Displays only the number of bytes in the input.
––lines
–l
(lowercase "l") Displays only the number of lines (that is, NEWLINE characters) in the input.
––max-line-length
–L
Displays the length of the longest line in the input.
––chars
–m
Displays only the number of characters in the input.
––words
–w
Displays only the number of words in the input.
which: Shows where in PATH a command is located
which command-list
xargs: Converts standard input into command lines
xargs [options] [command]
Options
––replace[=marker]
–i[marker]
Allows you to place arguments from standard input anywhere within command. All occurrences of marker in command for xargs are replaced by the arguments generated from standard input of xargs. If you omit marker, it defaults to the string { }, which matches the syntax used in the find command –exec option. With this option command is executed for each input line; the ––max-lines option is ignored when you use ––replace.
––max–lines[=num]
–l [num]
(lowercase "l") Executes command once for every num lines of input (num defaults to 1).
––max–args=num
–n num
Executes command once for every num arguments in the input line.
––interactive
–p
Prompts the user prior to each execution of command.
––max–procs=num
–P num
Allows xargs to run up to maxprocs instances of command simultaneously. (The default is 1, which runs commands sequentially.) This option may improve the throughput if you are running Linux on a multiprocessor system.
––no–run–if–empty
–r
Causes xargs not to execute command if standard input is empty. Ordinarily xargs executes command at least once, even if standard input includes only blanks.
< filename
Redirects standard input from filename.
> filename
Redirects standard output to filename unless filename exists and noclobber (page 119) is set. If noclobber is not set, this redirection creates filename if it does not exist.
>| filename
Redirects standard output to filename, even if the file exists and noclobber (page 119) is set.
>> filename
Redirects and appends standard output to filename unless filename exists and noclobber (page 119) is set. If noclobber is not set, this redirection creates filename if it does not exist.
<&m
Duplicates standard input from file descriptor m (page 471).
[n] >&m
Duplicates standard output or file descriptor n if specified from file descriptor m (page 471).
[n]<&–
Closes standard input or file descriptor n if specified (page 471).
[n] >&–
–Closes standard output or file descriptor n if specified.
if [ -f ~/.bashrc ]; then
source ~/.bashrc # read local startup file if it exists
fi
==========================================================
========================================================================
((fn += 1)) 等效于fn += 1自加操作
========================================================================
echo命令可以使用一些特殊的逃逸字符进行格式化输出,下面是这些字符及其含义:
\b Backspace
\c 显示后不换行
\f 在终端上屏幕的开始处显示
\n 换行
\r 回车
\t 制表符
\v 垂直制表符
\ 反斜框
\0nnn 用1,2或3位8进制整数表示一个ASCII码字符
用户可以比较两个字符串相等或不等,也可以测试一个串是否赋了值。有关串的操作符如下:
str1 = str2 当两个串有相同内容、长度时为真
str1 != str2 当串str1和str2不等时为真
-n str1 当串的长度大于0时为真(串非空)
-z str1 当串的长度为0时为真(空串)
str1 当串str1为非空时为真
$str1=abcd
$test $str1 = abcd
$echo $?
结果显示:0
int1 -eq int2 两数相等为真
int1 -ne int2 两数不等为真
int1 -gt int2 int1大于int2为真
int1 -ge int2 int1大于等于int2为真
int1 -lt int2 int1小于int2为真
int1 -le int2 int1小于等于int2为真
下面的例子反映了字符串比较与数字比较的不同:
$str1=1234
$str2=01234
$test $str1 = $str2
$echo $?
结果显示:1
$test $str1 -eq $str2
$echo $?
结果显示:0
3>有关文件的测试
使用test进行的第三类测试是测试文件的状态,用户可以测试文件是否存在,是否可写以及其他文件属性。下面是文件测试时使用的选项。注意只有文件存在时,才有可能为真。
-r file 用户可读为真
-w file 用户可写为真
-x file 用户可执行为真
-f file 文件为正规文件为真
-d file 文件为目录为真
-c file 文件为字符特殊文件为真
-b file 文件为块特殊文件为真
-s file 文件大小非0时为真
-t file 当文件描述符(默认为1)指定的设备为终端时为真
4>复杂的条件测试(and 、or 、not)
-a 与
-o 或
! 非
就是组合条件了,任何高级语言中都有的(NOT 、AND 、OR),例如:
$test -r em.null -a -s em.null
$echo $?
结果显示:1
说明了em.null并不是可读并且非空的文件
5>另一种执行test的方法
bsh中还有另一种执行test命令的方法,就是把测试条件放到一对[
]中,例如:
$int1=4
$[ $int1 -gt 2 ]
$echo $?
结果显示:0
6>空命令
在Bsh中用 : 代表空命令,就是充个数,什么都不做
Until语句
While语句中,只要某条件为真,则重复执行循环代码,until语句正好同while相反,该语句使循环代码重复执行,直到遇到某一条件为真才停止。
Until语句的结构如下:
until command
do
command
command
… …
done
可以用until语句替换上面备份程序的while语句,完成同样的功能:
until [ $ANS != Y -a $ANS != y ]
for 循环
在介绍for循环之前,我们要学个非常有用的unix命令:shift。我们知道,对于位置变量或命令行参数,其个数必须是确定的,或者当 Shell程序不知道其个数时,可以把所有参数一起赋值给变量$*。若用户要求Shell在不知道位置变量个数的情况下,还能逐个的把参数一一处理,也就是在$1后为$2,在$2后面为$3等。在
shift命令执行前变量$1的值在shift命令执行后就不可用了。
#测试shift命令(x_shift.sh)
until [ $# -eq 0 ]
do
echo "第一个参数为: $1 参数个数为: $#"
shift
done
执行以上程序x_shift.sh:
$./x_shift.sh 1 2 3 4
结果显示如下:
第一个参数为: 1 参数个数为: 3
第一个参数为: 2 参数个数为: 2
第一个参数为: 3 参数个数为: 1
第一个参数为: 4 参数个数为: 0
从上可知shift命令每执行一次,变量的个数($#)减一,而变量值提前一位,下面代码用until和shift命令计算所有命令行参数的和。
#shift上档命令的应用(x_shift2.sh)
if [ $# -eq 0 ]
then
echo "Usage:x_shift2.sh 参数"
exit 1
fi
sum=0
until [ $# -eq 0 ]
do
sum=`expr $sum + $1`
shift
done
echo "sum is: $sum"
执行上述程序:
$x_shift2.sh 10 20 15
其显示结果为:
45
shift命令还有另外一个重要用途,Bsh定义了9个位置变量,从$1到$9,这并不意味着用户在命令行只能使用9个参数,借助shift命令可以访问多于9个的参数。
用户也可以在命令行上同时对多个变量赋值,赋值语句之间用空格分开:
//对多变量进行赋值[luther.gliethttp]
$X=x Y=y
注意变量赋值是从右到左进行的
$X=$Y Y=y
X的值是y
$X=z Y=$Z
Y的值是空(变量未赋值时,shell不报错,而是赋值为空)
${variable: -value} variable是一变量值,value是变量替换使用的默认值
${variable:=value} 该形式在变量替换后同时把值value符给变量variable。
变量替换的值也可以是` `括起来的命令: $USERDIR={$Mydir: -`pwd`}
第三种变量的替换方法是只有当变量已赋值时才用指定值替换形式:
${variable: +value} 只有变量variable已赋值时,其值才用value替换,否则不进行任何替换,
我们还可以使用错误检查的条件进行变量替换:
${variable:?message}
当变量variable已设置时,正常替换。否则消息message将送到标准错误输出(若此替换出现在shell程序中,那么该程序将终止)。 例如:
$UNAME=
$echo $ {UNAME:?"UNAME HAS NOT BEEN SET"}
结果显示:UNAME HAS NOT BEEN SET
$UNAME=Stephanie
$echo $ {UNAME:?"UNAME HAS NOT BEEN SET"}
结果显示:Stephanie
当没有指定message时,shell将显示一条默认的消息,例如:
$UNAME=
$echo $ {UNAME:?}
结果显示:sh:UNAME:parameter null or not set
在shell解释用户的命令时,将把命令行的第一个字作为命令,而其他的字作为参数。当命令对应的可执行文件为Shell程序时,这些参数将作为位置变量传送给该程序。第一个参数记为$1,第二个为$2....第九个为$9。其中1到9是真正的参数名,"$"符只是用来标识变量的替换。
位置变量$0指命令对应的可执行文件名。
高级语言中变量是具有类型的,即变量将被限制为某一数据类型,如整数或字符类型。Shell变量通常按字符进行存储,为了对Shell变量进行算术运算,必须使用expr命令。
expr命令将把一个算术表达式作为参数,通常形式如下:
expr [数字] [操作符] [数字]
由于Shell是按字符形式存储变量的,所以用户必须保证参加算术运算的操作数必须为数值。下面是有效的算术操作符:
+ 两个整数相加
- 第一个数减去第二个数
* 两整数相乘
/ 第一个整数除以第二个整数
% 两整数相除,取余数
例如:
$expr 2 + 1
结果显示:3
$expr 5 - 3
结果显示:2
用户不能单纯使用"*"做乘法,若输入:
$expr 4*5
系统将会报错,因为Shell看到"*"将会首先进行文件名替换。正确形式为:
$expr 4 \* 5
结果显示:20
多个算术表达式可以组合在一起,例如:
$expr 5 + 7 / 3
结果显示:7
运算次序是先乘除后加减,若要改变运算次序,必须使用"`"号,如:
$int=`expr 5 + 7`
$expr $int/3
结果显示:4
或者:
$expr `expr 5+7`/3
结果显示:4
《摘自:》
"输入输出重定向及管道" :重定向的功能同DOS的重定向功能:
">" 重定向输出
"<" 重定向输入
"使用保留字":Shell有一些具有特殊意义的字,例如在Shell脚本中,do,done,for等字用来控制循环操作,if,then等控制条件操作。
保留字随Shell环境的不同而不同。
"通配符":* 匹配任何位置
? 匹配单个字符
[] 匹配的字符范围或列表 例如:
$ls [a-c]*
将列出以a-c范围内字符开头的所有文件
$ls [a,m,t]*
将列出以e,m或t开头的所有文件
.profile中shell的环境变量意思如下:
CDPATH 执行cd命令时使用的搜索路径
HOME 用户的home目录
IFS 内部的域分割符,一般为空格符、制表符、或换行符
MAIL 指定特定文件(信箱)的路径,有UNIX邮件系统使用
PATH 寻找命令的搜索路径(同dos的config.sys的 path)
PS1 主命令提示符,默认是"$"
PS2 从命令提示符,默认是">"
TERM 使用终端类型
2>Bsh里特殊字符及其含义
在Bsh中有一组非字母字符。这些字符的用途分为四类:作为特殊变量名、产生文件名、数据或程序控制以及引用和逃逸字符控制。他们
可以让用户在Shell中使用最少的代码完成复杂的任务。
*> Shell变量名使用的特殊字符
$# 传送给命令Shell的参数序号
$- 在Shell启动或使用set命令时提供选项
$? 上一条命令执行后返回的值
$$ 当前shell的进程号
$! 上一个子进程的进程号
$@ 所有的参数,每个都用双括号括起
$* 所有参数,用双括号括起
$n 位置参数值,n表示位置
$0 当前shell名
*>产生文件名的特殊字符
包括"*","?","[]",上面讲过,不再多说。
*>数据或程序控制使用的特殊字符
>(file) 输出重定向到文件中(没有文件则创建,有则覆盖)
>>(file)
输出重定向到文件中(没有则创建,有则追加到文件尾部)
<(file) 输入重定向到文件
; 命令分割符
| 管道符
& 后台运行(例如:sleep 10 &)
` ` 命令替换,重定向一条命令的输出作为另一命令的参数
*>对于引用或逃逸的特殊字符
Bsh用单引号' '和双引号"
"将特殊字符或由空白分隔的字引用起来组成一个简单的数据串.使用单引号和双引号的区别是双引号中的内容可进行参数和变量替换.逃逸字符也一样.
$echo "$HOME $PATH"
结果显示$/u/ice_walk/bin:/etc:/usr/bin
而$echo '$HOME $PATH' 结果显示$HOME $PATH
shell的逃逸符是一个"\",表示其后的字符不具有特殊的含义或不是shell的函数
$echo \$HOME $PATH
结果显$$HOME /bin:/etc:/usr/bin:
用户可以使用"unset <变量>"命令清除给变量赋的值
========================================================================
《摘自:http://blog.chinaunix.net/u1/38994/showart_1667799.html》
1.shell注释和python一样,都是以#开头
2.shell变量使用和pythony一样,都不需要声明变量,直接赋值
2.1
a="hello world"
echo $a
2.2
num=2
错误写法:echo "this is the $numnd"
正确写法:echo "this is the ${num}nd"
3.环境变量,由export关键字处理过的变量叫做环境变量.
常用命令语法及功能
echo "some text": 将文字内容打印在屏幕上
ls: 文件列表
wc –l filewc -w filewc -c file: 计算文件行数计算文件中的单词数计算文件中的字符数
cp sourcefile destfile: 文件拷贝
mv oldname newname : 重命名文件或移动文件
rm file: 删除文件
grep 'pattern' file: 在文件内搜索字符串比如:grep 'searchstring' file.txt
cut -b colnum file: 指定欲显示的文件内容范围,并将它们输出到标准输出设备比如:输出每行第5个到第9个字符cut -b5-9 file.txt千万不要和cat命令混淆,
这是两个完全不同的命令
cat file.txt: 输出文件内容到标准输出设备(屏幕)上
file somefile: 得到文件类型
read var: 提示用户输入,并将输入赋值给变量
sort file.txt: 对file.txt文件中的行进行排序
uniq: 删除文本文件中出现的行列比如: sort file.txt | uniq
expr: 进行数学运算Example: add 2 and 3expr 2 "+" 3
find: 搜索文件比如:根据文件名搜索find . -name filename -print
tee: 将数据输出到标准输出设备(屏幕) 和文件比如:somecommand | tee outfile
basename file: 返回不包含路径的文件名比如: basename /bin/tux将返回 tux
dirname file: 返回文件所在路径比如:dirname /bin/tux将返回 /bin
head file: 打印文本文件开头几行
tail file : 打印文本文件末尾几行
sed: Sed是一个基本的查找替换程序。可以从标准输入(比如命令管道)读入文本,并将
结果输出到标准输出(屏幕)。该命令采用正则表达式(见参考)进行搜索。不要和shell中的通配符相混淆。比如:将linuxfocus 替换为LinuxFocus :cat text.file | sed 's/linuxfocus/LinuxFocus/' > newtext.file awk: awk 用来从文本文件中提取字段。缺省地,字段分割符是空格,可以使用-F指定其他分割符。
cat file.txt | awk -F, '{print $1 "," $3 }'这里我们使用,作为字段分割符,同时打印第一个和第三个字段。如果该文件内容如下: Adam Bor, 34, IndiaKerry Miller, 22, USA命令输出结果为:Adam Bor, IndiaKerry Miller, USA
2) 概念: 管道, 重定向和 backtick
这些不是系统命令,但是他们真的很重要。
管道 (|) 将一个命令的输出作为另外一个命令的输入。
grep "hello" file.txt | wc -l
在file.txt中搜索包含有”hello”的行并计算其行数。
在这里grep命令的输出作为wc命令的输入。当然您可以使用多个命令。
重定向:将命令的结果输出到文件,而不是标准输出(屏幕)。
> 写入文件并覆盖旧文件
>> 加到文件的尾部,保留旧文件内容。
反短斜线
使用反短斜线可以将一个命令的输出作为另外一个命令的一个命令行参数。
命令:
find . -mtime -1 -type f -print
用来查找过去24小时(-mtime –2则表示过去48小时)内修改过的文件。如果您想将所有查找到的文件打一个包,则可以使用以下脚本:
#!/bin/sh
# The ticks are backticks (`) not normal quotes ('):
tar -zcvf lastmod.tar.gz `find . -mtime -1 -type f -print`
3) 流程控制
1.if
"if" 表达式 如果条件为真则执行then后面的部分:
if ....; then
....
elif ....; then
....
else
....
fi
通常用" [ ] "来表示条件测试。注意这里的空格很重要。要确保方括号的空格。
[ -f "somefile" ] :判断是否是一个文件
[ -x "/bin/ls" ] :判断/bin/ls是否存在并有可执行权限
[ -n "$var" ] :判断$var变量是否有值
[ "$a" = "$b" ] :判断$a和$b是否相等
熟悉C语言的朋友可能会很喜欢下面的表达式:
[ -f "/etc/shadow" ] && echo "This computer uses shadow passwors"
这里 && 就是一个快捷操作符,如果左边的表达式为真则执行右边的语句。
您也可以认为是逻辑运算中的与操作。上例中表示如果/etc/shadow文件存在则打印” This computer uses shadow passwors”。同样或操作(||)在shell编程中也是可用的。这里有个例子:
2.case
case :表达式可以用来匹配一个给定的字符串,而不是数字。
case ... in
...) do something here ;;
esac
让我们看一个例子。 file命令可以辨别出一个给定文件的文件类型,比如:
file lf.gz
这将返回:
3. selsect
select 表达式是一种bash的扩展应用,尤其擅长于交互式使用。用户可以从一组不同的值中进行选择。
select var in ... ; do
break
done
.... now $var can be used ....
下面是一个例子:
#!/bin/sh
echo "What is your favourite OS?"
select var in "Linux" "Gnu Hurd" "Free BSD" "Other"; do
break
done
echo "You have selected $var"
下面是该脚本运行的结果:
What is your favourite OS?
1) Linux
2) Gnu Hurd
3) Free BSD
4) Other
#? 1
4.loop
loop表达式:
while ...; do
....
done
while-loop 将运行直到表达式测试为真。will run while the expression that we test for is true.
关键字"break" 用来跳出循环。而关键字”continue”用来不执行余下的部分而直接跳到下一个循环。
for-loop表达式查看一个字符串列表 (字符串用空格分隔) 然后将其赋给一个变量:
for var in ....; do
....
done
在下面的例子中,将分别打印ABC到屏幕上:
#!/bin/sh
for var in A B C ; do
echo "var is $var"
done
4)函数
如果您写了一些稍微复杂一些的程序,您就会发现在程序中可能在几个地方使用了相同的代码,并且您也会发现,如果我们使用了函数,会方便很多。一个函数是这个样子的:
functionname()
{
# inside the body $1 is the first argument given to the function
# $2 the second ...
body
}
您需要在每个程序的开始对函数进行声明。
下面是一个叫做xtitlebar的脚本,使用这个脚本您可以改变终端窗口的名称。
这里使用了一个叫做help的函数。正如您可以看到的那样,这个定义的函数被使用了两次。
#!/bin/sh
# vim: set sw=4 ts=4 et:
help()
{
cat <
xtitlebar -- change the name of an xterm, gnome-terminal or kde konsole
USAGE: xtitlebar [-h] "string_for_titelbar"
OPTIONS: -h help text
EXAMPLE: xtitlebar "cvs"
HELP
exit 0
}
# in case of error or if -h is given we call the function help:
[ -z "$1" ] && help
[ "$1" = "-h" ] && help
# send the escape sequence to change the xterm titelbar:
echo -e "33]0;$107"
#
阅读(4023) | 评论(0) | 转发(0) |