The set
command is used to define variables of any type. In addition, the set
command will return the value of a variable if it is only passed a
single argument. It treats that argument as a variable name and returns
the current value of the variable.
You can delete a variable with the unset command:
unset varName varName2 ...
The existence of a variable can be tested with the info exists command.
e.g.
if ![info exists foobar]{
set foobar 0
} else {
incr foobar }
The Tcl list has the same structure as a Tcl command. That is, a
list is simply a string with list elements separated by white
space.Braces or quotes can be used to group words with whitespace into
a single list element.
The list
command constructs a list out of its arguments such that there is one
list element for each argument. if any of the arguments contain special
characters, the list command adds some quoting to ensure they are
parsed as a single element of the resulting list.
e.g. Constructing a list with the list command
set x {1 2}
=> 1 2
set x
=> 1 2
list $x /$ foo
=> {1 2} {$} foo
[Note]: The braces used to group the list value into one argument to the set command are not part of the list value.
The lappend command is used to append elements to the end of a list. You can call lappend with the name of an undefined variable and the variable will be created.
e.g.
lappend new 1 2
=> 1 2
lappend new 3 "4 5"
=> 1 2 3 {4 5}
set new
=> 1 2 3 {4 5}
The concat
command is useful for splicing together lists. It works by
concatenating its arguments together, separating them with spaces. This
multiple lists into one where the top-level list elements in each input
list are also top-level list elements in the resulting list.
e.g. Using concat to splice together lists.
concat 1 {2 3} {4 5 6}
=> 1 2 3 4 5 6
It turns out that double quotes behave much like the concat command.
e.g. Double quotes compared to the list command.
set x {1 2}
=> 1 2
set y "$x 3"
=> 1 2 3
set y [concat $x 3]
=> 1 2 3
set z [list $x 3]
=>{1 2} 3
The basic rule is that list and lappend preserve preserve list structure, while concat(or double-quotes)eliminate one level of list structure.
The llength command returns the number of elements in a list.
The lindex command returns a particular element of a list. It takes an index. List indices count from zero. The keyword end means the last element, and it can be used with lindex, linsert, lrange and lreplace.
e.g.
lindex {1 2 3} 0
=> 1
lindex {1 2 3} 2
=> 3
The lrange command returns a range of list elements. It takes a list and two indices as arguments.
e.g.
lrange {1 2 3 {4 5}} 2 end
=> 3 {4 5}
The linsert
command inserts elements into a list value at a specified index. If the
index is 0 or less, then elements are added to the front. If the index
is equal to or greater than the length of the list, then the elements
are appended to the end. Otherwise, the elements are inserted before
the element that is currentl as position index.
lreplace
is used to replace a range of list elements with new elements. If you
don't specify any new elements, you effectively delete elements from a
list.
e.g.
linsert {1 2} 0 new stuff
=> new stuff 1 2
set x [list a {b c} e d]
=> a {b c} e d
lreplace $x 1 2 B C
=> a B C d
lreplace $x 0 0
=> {b c} e d
lsearch returns the index of a value in the list, or -1 if it is not present. lsearch supports pattern matching in its search. Glob-style pattern matching is default, and this canbe disabled with the -exact flag.
The example below uses lreplace to delete elements by not specifying any replacement list elements.
e.g.
proc delete {list value} {
set ix [lsearch -exact $list $value]
if {$ix>=0} {
return [lreplace $list $ix $ix]
} else {
return $list
}
}
The three basic types of sorts are specified with the -ascii, -integer, or -real options. The -increasing or -decreasing option indicate the sirting order. The default option set is -ascii -increasing.
The split command The The join command The index of an array is delimited by parentheses. The If
The array names command is perhaps the most useful because it allows easy iteration through an array with a foreach loop: In UNIX, the process environment variables are available through the global array env. The trace command lets you register a command to be called whenever a variable is accessed, modified or unset. The form is: Information about traces on a varible is returned with the vinfo option.8 The split And join Commands
takes a string and turns it into a list by breaking it at specified
characters. Stray double-quotes or curly braces in the input can result
in invalid list structures and errors in your script. However, the
split command provides a robust way to turn input lines into proper Tcl
lists.
default split character is white space. If there are multiple separator
characters in a row, these result in empty list elements- the
separators are not collapsed. The following command splits on commas,
periods, spaces and tabs:
is the inverse of split. It takes a list value and reformats it with
specified characters separating the list elements. In doing so, it will
remove any curly braces from the string representation of the list that
are used to group the top-level elements.
9 Arrays
index can have any string value, and it canbe the result of variable or
command substitution.
e.g. set arra(index) value
The value of an array element is obtained with $ substitution:
e.g. set foo $arr(index)
you have complex indices, use a comma to separate different parts of
the index. Avoid putting a pace after the comma. It is legal, but a
space in an index value will cause problems because parenthesis are not
used as a grouping mechanism. The space in the index needs to be quoted
with a backslash, or hte whole variable reference needs to be grouped:
e.g. set {arr(I'm asking for trouble)} {I told you so.}
If
the array index is stored in a variable, then there is no problem with
spaces in the variable's value. The following works fine:
e.g.
set index {
set arr($index) {I told you so.}
The
name of the array can be the result of a substitution. If the name of
the array is stored in another variable, then you must use set as shown
in the last command below to reference the array elements.
10 The Array Command
foreach index [array names arr] {command body}
The order of the names returned by array names is
arbitrary. It is essentially determined by the hash table
implementation of the array.
The array get and array set operations are used to convert between an array and a list. The list returned by array get
has an even number of elements.The first element is an index, and the
next is the corresponding array value. The ordering of the indexes is
arbitrary. The list argument to array set must have the same structure.11 Environment Variables
The name of the environment variable is the index,e.g. env(PATH), and
the array element contains the current value of the environment
variable.12 Tracing Variable Values
trace variable name ops command
The name is a Tcl variable name, which can be a simple
variable, an array or a element.If a whole array is traced, then the
trace is invoked when any element is used according to ops. The ops
argument is one or more of the letters: r for read traces, w for write
traces, and u for unset traces. The command is executed when one of
these events occurs. It is invoked as:
command name1 name2 op
trace vinfo dynamic
=> {r FixDynamic}
A trace is deleted with the vdelete trace option, which has the same form as the varible option.
In Tcl, evrything is a string, and you have to explicitly ask for evaluation of variables and nested commands.
Backslash(/) is used to quote characters that have special meaning to the interpreter.
You can also specify characters that are hard to type directly by giving their octal or hexadecimal value.
Another common use of backslashes is to continue long commands on
multiple lines. A backslash as the last character in a line is
converted into a space.
Double quotes, like braces, are used to group words together. The
difference between double quotes and curly braces is that quotes allow
substitutions to occur in the group, while curly braces prevent
substitutions.
Another common use of quotes is with the format command
that is similar to C printf function. The only way to effectively group
special characters in format command into a single argument is with
quotes.
e.g. puts [format "Item: %s/t%5.3f" $name $value]
Tcl uses the proc command to define procedures. The syntax is :
proc name arglist body
The return
command in Tcl procedure is optional because the interpreter will
return the value of the last command in the body as the value of the
procedure.
Grouping
decisions are made before substitutions are performed. This means that
the values of variables or command results do not affect grouping.
A
single round if substitutions is performed before command invocation.
That is, the result of a substitution is not interpreted a second time.
This rule is important if you have a variable value or a command result
that contains special characters such as spaces, dollar-signs, square
brackets or braces. Because only a single round of substitution is
done, you don't have to worry about special characters in values
causing extra substitutions.
Tcl
uses # for comments. Unlike many languages, the # character must occur
at the begining of a command. An easy trick to append a comment to the
end of a command is to proceed the # with a semicolon in order to
terminate the previous command.
A backslash(/)
continues a comment line onto the next line of the script. In addition,
a semi-colon inside a comment is not significant. only a newline
terminates comments.
<style>
st1/:*{behavior:url(#ieooui) }
</style>
<![endif]-->
The Ten Lesser Tenets
The /etc/passwd file determines
which shell takes effect during your interactive UNIX session.
/etc/passwd also contains account
info, which includes UID and GID.
Each process can have one or more
child process. If you kill the parent of a child process, it automatically
becomes the child of init.
init is the last process
created at boot time. It always has a process ID (PID) of 1 (i.e. on all
Unixes). init is responsible for starting all subsequent processes.
Consequently, it is the parent (in other words, mother of all processes!) of
all (non-dummy) Unix processes.
For each new process created, the
kernel sets up an address space in memory. This address space consists of the
following logical segments:
• text - contains the program's instructions.
• data - contains initialized program variables.
• bss - contains uninitialized program variables.
• stack - a dynamically growable segment, it contains
variables allocated locally
and parameters passed to
functions in the program.
1)
Context of Process & Context Switching
The context of a process is essentially a snapshot of its current
runtime environment, including its address space, stack space, etc. At any
given time, a process can be in user-mode, kernel-mode, sleeping, waiting on
I/O, and so on. The process scheduling subsystem within the kernel uses a time
slice of typically 20ms to rotate among currently running processes. Each
process is given its share of the CPU for 20ms, then left to sleep until its turn
again at the CPU. This process of moving processes in and out of the CPU is
called context switching. The kernel
makes the operating system appear to be multi-tasking (i.e. running processes
concurrently) via the use of efficient context-switching.
2)
Process status:
R - runable, currently on the run
queue
S - currently sleeping (waiting
on a pipe, completion of I/O, terminal input, memory)
T - currently stopped
Z - defunct or zombie (a process
with no swappable image but a structure in memory)
3)
Signal:
SIGHUP 1 Hangup
SIGINT 2 Interrupt
SIGKILL 9 Kill (cannot be
caught or ignore)
SIGTERM 15 Terminate
(termination signal from SIGKILL)
(1) Boot System
Boot scripts are normal shell
scripts. The boot scripts will execute by “init” process through sh. Boot
scripts’ task include set computer name, set timezone, check hard disk with
fsck, install file system, configure network interface, start daemon process
and network services, start log and disk quota etc.
BSD doesn’t have run level. ATT
System V has run level define in /etc/inittab.
(2) Shutdown System
·
Poweroff
( !!! may damage system )
·
Shutdown
( good way )
·
halt (
will change system to single user mode )
·
reboot
·
init or
telinit ( change the run level )
”su <account>” only change to another user’s
account. “su – <account>“ will excute
user’s profile while changing.
“su” or “su –“ without any account parameter means
you hope to change to
superuser(root).
1)
setup user environment in ksh
·
$HOME/.profile
·
shell variables: varname=value
·
unset variables
·
aliases
·
options
Any variable can become an
environment variable with the command:
export varnames.
environment file will told sub
process other variables, options, aliases that shell wish to told it. Environment
file name can be any name, as long as you set the environment variable ENV to
the file's name.
Alias
is a synonym for a command or command string. You define an alias by entering
(or adding to your .profile) a line with the following form: alias new=original
Options
let you change the shell's behavior. The basic commands that relate to options
are set -o optionnames and set +o optionnames, where optionnames
is a list of option names separated by blanks. the - turns the named option on, while the + turns it off.
2)
Built-in Variables
1)
Erase Character
·
[BACKSPACE]
·
[DELETE], [DEL] key
·
[CTRL-H]
2)
Other Control Characters
·
[CTRL-U] Erases
the whole input line; you can start over.
·
[CTRL-S] Pauses
output from a program that is writing to the screen.
·
[CTRL-Q] Restarts
output after a pause by [CTRL-S].
·
[CTRL-D] Used
to signal end-of-input for some programs.
super block describes the state of the file system: the total size
of the partition, the block size, pointers to a list of free blocks, the inode
number of the root directory, magic number, etc.
xargs [options] [command]
Execute command (with any initial
arguments), but read remaining arguments from standard input instead of
specifying them directly. xargs passes these arguments in several bundles to
command, allowing command to process more arguments than it could normally
handle at once. The arguments are typically a long list of filenames (generated
by ls or find, for example) that get passed to xargs via a pipe.
Example:
grep for pattern in all files on
the home directory /home/foo:
find /home/foo -print | xargs grep pattern > out &
(1) Searching Commands
·
… find
·
… grep
·
… egrep
·
… fgrep
① find pathname(s)
condition(s)
find descends the directory tree
beginning at each pathname and locates files that meet the specified
conditions. At least one pathname and one condition must be specified. The most
useful conditions include -print (which must be explicitly given to display any
output), -name and -type (for general use), -exec and -size (for advanced
users), and -mtime and -user (for administrators). Examples:
find $HOME –print
find $HOME –name ‘core’ –exec rm –rf {} /;
② grep [options] regexp [files]
Search one or more files for
lines that match a regular expression regexp. Examples:
List the number of users who use
the korn shell:
grep -c /bin/ksh /etc/passwd
List header files that have at
least one #include directive:
grep -l '^#include' /usr/include/*
List files that don't contain
pattern:
grep -c pattern files | grep :0
(2) Patterns (Regular Expressions
)
A regular expression describes a pattern
or a particular sequence of characters, although it does not necessarily
specify a single exact sequence. Pattern is composed of mixed sequence of
characters and metacharacters.
(1) Backup & Compression
tar
cpio
dd
compress
uncompress
unzip
gzip/gunzip/zcat
bzip2/bzcat
filename suffix
. .tar
. .Z
. .gz
. .tar.Z
. .tar.gz
. .zip
. .bz; .tar.bz
(2) Text Processing
cut Select columns for display.
join Merge different columns into a database.
paste Merge columns or switch order.
sort Sort or merge files.
tr Translate (redefine) characters.
uniq Find repeated or unique lines in a file.
sed Stream editor, edit one or more files without user
interaction
awk Use the pattern-matching program to modify the
specified files
(3) Job Control
jobs
fg
bg
ps
kill
(4) Communication and network
utilities
ftp
rsh/remsh
$HOME/.rhosts
rup
mailx
$HOME/.forward
ping
netstat
ifconfig
1 Perl中所有数字内部格式一致,只有双精度浮点数(Perl内部没有整数值)。
2 Perl中允许用下划线来分隔比较长的整数,如612980400283768和612_980_400_283_768是相同的值。
3 Perl中的非十进制整数:八进制以0开头,十六机制以0x开头,二进制以0b开头。
4 Perl中的数字操作符除加减乘除之外,还有模数运算符(%)和指数操作符(**)。对于%,两个操作数首先变成对应的整数值,如10.5%3.2首先变成10%3后再计算。在模数运算中,如果有一个操作数为负数,其结果和Perl的具体实现有关。另外,通常不能进行一个负数的非整数次方的运算(这将产生一个复数),除非有了Math::Complex模块。
5 单引号字符串
单引号不是字符串的一部分,但Perl可以用它辨别字符串的开始和结束。除了单引号或者反斜线(包括换行字符,如果字符串在下一行继续)之外的任何字符都表示它自身。要得到一个反斜线,可以把两个反斜线放在一起;要得到单引号,需要在单引号之前加上反斜线。单引号字符串中的/n不会被当作换行符来处理,其仅仅是两个字符/和n。只有在反斜线后面接的是/或者是单引号'才会被当作特殊字符来处理。
6 双引号字符串
双引号字符串中/n为换行符。双引号中的转义字符:
------------------------------
| 符号 | 含义 |
------------------------------
| /n | 换行 |
------------------------------
| /r | 回车 |
------------------------------
| /t | 制表符 |
------------------------------
| /f | formfeed |
------------------------------
| /b | 退格 |
------------------------------
| /a | 响铃 |
------------------------------
| /e | escape(ASCII中的escape字符) |
------------------------------
| /007 | 任何八进制值(这里是007=bell) |
------------------------------
| /x7f | 任何十六进制值(这里是007=bell) |
------------------------------
| /cC | 一个控制符(这里是Ctrl+c) |
------------------------------
| // | 反斜线 |
------------------------------
| /" | 双引号 |
------------------------------
| /l | 下个字符小写 |
------------------------------
| /L | 接下来的字符均小写直到/E |
------------------------------
| /u | 下个字符大写 |
------------------------------
| /U | 接下来的字符均大写知道/E |
------------------------------
| /Q | 在non-word字符之前加上/,直到/E |
------------------------------
| /E | 结束/L, /E和/Q |
------------------------------
双引号字符串的另一个性质是可以进行变量内插,也即当使用字符串时,如果字符串中含有变量名,将由变量的当前值替换它。
7 字符串操作符
字符串可由.操作符连接。
字符串重复操作符为小写字母x,如"fred" x 3 #"fredfredfred", 5 x 4 #实际上是"5555"。
8 数字和字符串之间的自动转换
Perl将在需要的时候根据标量值之间的操作符自动进行数字和字符串之间的自动转换。
9 Perl中的标量变量都形如$fred。当一个字符串由双引号括起来时,如果变量前没有反斜线,则变量的值会被替换(如果一个变量未被赋值,则将使用空值)。Perl提供了分隔符{}将变量名括起来,如:
$what="brontosaurus steak";
$n=3;
print "fred ate $n $whats./n"; #输出不是steaks,而是$whats的值
print "fred ate $n ${what}s./n"; #现在使用$what的值。
10 Perl中没有Boolean类型,但可以利用一下几条法则帮助记忆:
如果值为数字,0是false,其余为真;
如果值为字符串,则空串('')为false,其余为真;
如果值的类型既不是数字又不是字符串,则将其转换为数值或字符串再利用上述规则。
11 行输入运算符:<STDIN>。<STDIN>作为标量值来使用,Perl每次在标准输入中读入文本下一行,将其传给<STDIN>。利用<STDIN>读入的字符串行尾是有换行符的,可以利用chomp函数来去掉。chomp是一个函数,作为函数它有一个返回值,为移除的字符的个数。在使用chomp时,可以使用或不使用(),这又是perl中的一条通用规则:除非移除它们会改变含义,否则括号是可以省略的。如果结尾有两个或两个以上的换行符,chomp仅去掉一个。
12 undef值
Perl中,变量在第一次赋值前有一个特殊值undef,如果该变量是数值型,则undef为0;如果是字符串,则undef为空串。
13 defined函数
~/.profile 是在用户的主目录下的一个文件,每次用户登陆都会执行这里边的ENV环境变量设置。
/etc/profile是一个全局的环境变量设置,只要登陆系统的用户都会执行里面的ENV环境变量设置
~/.kshrc是在用户的主目录下面的,每次执行KSH下面的子shell的时候,都会执行这里面的ENV环境变量设置。
~/.dtprofile是在用户的主目录下面的,在这里设置你进入CDE时的一些变量设置,如果用户没有通过CDE进入过系统,那么将不会产生这个文件,只有用户曾经用CDE进入过系统后就会自动生成一个.dtprofile文件,然后还可以对里边的变量进行设置。。
如果在这个文件里的DTSOURCEPROFILE的变量设置为true则会读取用户瞩目路下的.profile文件里的变量设置,如果没有这个变量或者设置为false,那么将不读取.profile里的环境变量。
如果想让刚刚改变的.profile .kshrc里面的设置马上生效使用,可以使用以下的命令:
. ~/.profile
. ~/.kshrc
http://www.cppreference.com/operator_precedence.html
C++ 运算符优先级列表
Precedence
Operator
Description
Example
Associativity
1
()
[]
->
.
::
++
--Grouping operator
Array access
Member access from a pointer
Member access from an object
Scoping operator
Post-increment
Post-decrement(a + b) / 4;
array[4] = 2;
ptr->age = 34;
obj.age = 34;
Class::age = 2;
for( i = 0; i < 10; i++ ) ...
for( i = 10; i > 0; i-- ) ...left to right
2
!
~
++
--
-
+
*
&
(type)
sizeofLogical negation
Bitwise complement
Pre-increment
Pre-decrement
Unary minus
Unary plus
Dereference
Address of
Cast to a given type
Return size in bytesif( !done ) ...
flags = ~flags;
for( i = 0; i < 10; ++i ) ...
for( i = 10; i > 0; --i ) ...
int i = -1;
int i = +1;
data = *ptr;
address = &obj;
int i = (int) floatNum;
int size = sizeof(floatNum);right to left
3
->*
.*Member pointer selector
Member pointer selectorptr->*var = 24;
obj.*var = 24;left to right
4
*
/
%Multiplication
Division
Modulusint i = 2 * 4;
float f = 10 / 3;
int rem = 4 % 3;left to right
5
+
-Addition
Subtractionint i = 2 + 3;
int i = 5 - 1;left to right
6
<<
>>Bitwise shift left
Bitwise shift rightint flags = 33 << 1;
int flags = 33 >> 1;left to right
7
<
<=
>
>=Comparison less-than
Comparison less-than-or-equal-to
Comparison greater-than
Comparison geater-than-or-equal-toif( i < 42 ) ...
if( i <= 42 ) ...
if( i > 42 ) ...
if( i >= 42 ) ...left to right
8
==
!=Comparison equal-to
Comparison not-equal-toif( i == 42 ) ...
if( i != 42 ) ...left to right
9
&
Bitwise AND
flags = flags & 42;
left to right
10
^
Bitwise exclusive OR
flags = flags ^ 42;
left to right
11
|
Bitwise inclusive (normal) OR
flags = flags | 42;
left to right
12
&&
Logical AND
if( conditionA && conditionB ) ...
left to right
13
||
Logical OR
if( conditionA || conditionB ) ...
left to right
14
? :
Ternary conditional (if-then-else)
int i = (a > b) ? a : b;
right to left
15
=
+=
-=
*=
/=
%=
&=
^=
|=
<<=
>>=Assignment operator
Increment and assign
Decrement and assign
Multiply and assign
Divide and assign
Modulo and assign
Bitwise AND and assign
Bitwise exclusive OR and assign
Bitwise inclusive (normal) OR and assign
Bitwise shift left and assign
Bitwise shift right and assignint a = b;
a += 3;
b -= 4;
a *= 5;
a /= 2;
a %= 3;
flags &= new_flags;
flags ^= new_flags;
flags |= new_flags;
flags <<= 2;
flags >>= 2;right to left
16
,
Sequential evaluation operator
for( i = 0, j = 0; i < 10; i++, j++ ) ...
left to right
The trap command is used to specify the
actions to take on receipt of signals. A common use is to tidy up a
script when it is interrupted.
The trap command is passed the action to take, followed by the signal name (or names) to trap on:
To see the signal numbers and associated names, you can just type trap -l at a command prompt.
To reset a trap condition to the default, simply specify the command as
-. To ignore a signal, set the command to the empty string ‘’.
Signal Description
HUP (1) Hang up; usually sent when a terminal goes offline, or a user logs out
INT (2) Interrupt; usually sent by pressing Ctrl+C
QUIT (3) Quit; usually sent by pressing Ctrl+/
ABRT (6) Abort; usually sent on some serious execution error
ALRM (14) Alarm; usually used for handling timeouts
TERM (15) Terminate; usually sent by the system when it’s shutting down
(22) unset
The unset command removes variables or functions from the environment.
It can’t do this to read-only variables defined by the shell itself,
such as IFS.
(23) find
The full syntax for the find command is as follows:
find [path] [options] [tests] [actions]
Option Meaning
-depth Search the contents of a directory before looking at the directory itself.
-follow Follow symbolic links.
-maxdepths N Search at most N levels of the directory when searching.
-mount (or -xdev) Don’t search directories on other file systems.
Test Meaning
-atime N The file was last accessed N days ago.
-mtime N The file was last modified N days ago.
-name pattern The name of the file, excluding any path, matches the pattern pro-
vided. To ensure that the pattern is passed to find, and not evaluated
by the shell immediately, the pattern must always be in quotes.
-newer otherfile The file is newer than the file otherfile.
-type C The file is of type C, where C can be of a particular type; the most
common are “d” for a directory and “f” for a regular file. For other
types consult the manual pages.
-user username The file is owned by the user with the given name.
Operator, Short Form Operator, Long Form Meaning
! -not Invert the test.
-a -and Both tests must be true.
-o -or Either test must be true.
Action Meaning
-exec command Execute a command. This is one of the most common actions. See the
explanation following this table for how parameters may be passed to
the command. This action must be terminated with a /; character pair.
-ok command Like -exec, except that it prompts for user confirmation of each file on
which it will carry out the command before executing the command.
This action must be terminated with a /; character pair.
-print Print out the name of the file.
-ls Use the command ls -dils on the current file.
(24) grep
The grep command takes options, a pattern to match, and files to search in:
grep [options] PATTERN [FILES]
Option Meaning
-c Rather than print matching lines, print a count of the number of linesthat match.
-E Turn on extended expressions.
-h Suppress the normal prefixing of each output line with the name of the file it was found in.
-i Ignore case.
-l List the names of the files with matching lines; don’t output the actual matched line.
-v Invert the matching pattern to select nonmatching lines, rather than matching lines.
(25) Regular Expressions
The most frequently used are shown in the following table:
Character Meaning
^ Anchor to the beginning of a line
$ Anchor to the end of a line
. Any single character
[ ] The square braces contain a range of characters, any one of which
may be matched, such as a range of characters like a–e or an inverted
range by preceding the range with a ^ symbol.
If you want to use any of these characters as “normal” characters, precede them with a /.
There are also some useful special match patterns that can be used in square braces, as described in the following table:
Match Pattern Meaning
[:alnum:] Alphanumeric characters
[:alpha:] Letters
[:ascii:] ASCII characters
[:blank:] Space or tab
[:cntrl:] ASCII control characters
[:digit:] Digits
[:graph:] Noncontrol, nonspace characters
[:lower:] Lowercase letters
[:print:] Printable characters
[:punct:] Punctuation characters
[:space:] Whitespace characters, including vertical tab
[:upper:] Uppercase letters
[:xdigit:] Hexadecimal digits
In addition, if the -E
for extended matching is also specified, other characters that control
the completion of matching may follow the regular expression (see the
following table). With grep it is also necessary to precede these
characters with a /.
Examples:
$ grep "e$" words2.txt # this finds lines that end in the letter e.
$ grep a[[:blank:]] words2.txt # find words that end with the letter a. [[:blank:]] tests for a space or a tab
$ grep -E [a-z]/{10/} words2.txt #
use the extended grep mode to search for lowercase words that are
exactly 10 characterslong. Do this by specifying a range of
# characters
to match a to z, and a repetition of 10 matches
(26) Command Execution
Execute a command and put the output of the command into a variable. You can do this by using the $(command) syntax.The result of the $(command) is simply the output from the command. If you want to get the result into a variable, you can just assign it in the usual way:
whoisthere=$(who)
echo $whoisthere
(27) Arithmetic Expansion
The expr
command can enable simple arithmetic commands to be processed, but this
is quite slow to execute because a new shell is invoked to process the expr command.
A newer and better alternative is $((...)) expansion. By enclosing the expression you wish to evaluate in $((...)), you can perform simple arithmetic much more efficiently.
#!/bin/sh
x=0
while [ "$x" -ne 10 ]; do
echo $x
x=$(($x+1))
done
exit 0
(28) Parameter Expansion
These
substitutions are often useful when you’re working with strings. The
last four, which remove parts of strings, are especially useful for
processing filenames and paths, as the following example shows.
#!/bin/sh
unset foo
echo ${foo:-bar}
foo=fud
echo ${foo:-bar}
foo=/usr/bin/X11/startx
echo ${foo#*/}
echo ${foo##*/}
bar=/usr/local/etc/local/networks
echo ${bar%local*}
echo ${bar%%local*}
exit 0
The output is:
bar
fud
usr/bin/X11/startx
startx
/usr/local/etc
/usr
(29) Here Document
One
special way of passing input to a command from a shell script is to use
a here document. This document allows a command to execute as though it
were reading from a file or the keyboard, whereas in fact it’s getting
input from the script.
A here document starts with the leader <<, followed by a special sequence of characters that is repeated at the end of the document. <<
is the shell’s label redirector, which in this case forces the command
input to be the here document. This special sequence acts as a marker
to tell the shell where the here document ends. The marker sequence
must not appear in the lines to be passed to the command, so it’s best
to make them memorable and fairly unusual.
#!/bin/sh
cat <<!FUNKY!
hello
this is a here
document
!FUNKY!
4.7 Debugging Shell
Since scripts are interpreted, there’s no compilation overhead in
modifying and retrying a script. The main way to trace more complicated
errors is to set various shell options. To do this, you can either use
command-line options after invoking the shell or use the set command.
The following table summarizes the options:
4.8 Dialog Utility
Example1:
#!/bin/sh
# Ask some questions and collect the answer
dialog --title "Questionnaire" --msgbox "Welcome to my simple survey" 9 18
dialog --title "Confirm" --yesno "Are you willing to take part?" 9 18
if [ "$?" != 0 ]; then
dialog --infobox "Thank you anyway" 5 20
sleep 2
dialog --clear
exit 0
fi
dialog --title "Questionnaire" --inputbox "Please enter your name" 9 30 2>_1.txt
Q_NAME=$(cat _1.txt)
dialog --menu "$Q_NAME, what music do you like best?" 15 30 4 1 "Classical" 2 "Jazz" 3 "Country" 4 "Other" 2>_1.txt
Q_MUSIC=$(cat _1.txt)
if [ "$Q_MUSIC" = "1" ]; then
dialog --title "Likes Classical" --msgbox "Good choice!" 12 25
else
dialog --title "Doesn’t like Classical" --msgbox "Shame" 12 25
fi
sleep 2
dialog --clear
exit 0
Explanation:
You start with a simple welcome screen, before asking the user if he will take part using the simple --yesno option of dialog. You use the $? variable to check the reply. If he agreed, you then get his name, store it in a variable Q_NAME, and ask what sort of music he likes, using the --menu option of dialog. By storing the numerical output in the variable Q_MUSIC, you can see what he answered, and give an appropriate response.
(9) break (11) Continue (15) export (16) expr (17) printf This program sets the parameter list to the date command’s output and then uses the positional parameter $2 to get at the month.Since the date command is sensitive to the language locale, in reality you would have extracted the name of the month using date +%B. The most commonly used form of the command is set -x, which makes a script display a trace of its currently executing command. (20) Shift
function_name () {
statements
}
foo () { echo JAY;}
The eval command enables you to evaluate arguments. It’s built into the shell and doesn’t normally exist as a separate command. eval is a bit like an extra $: It gives you the value of the value of a variable.
The exec command has two different uses. Its typical use is to replace the current shell with a different program.
The second use of exec is to modify the current file descriptors:
exec 3< afile
This causes file descriptor three to be opened for reading from file afile. It’s rarely used.
The export command creates an environment variable from its parameter that can be seen by other scripts and programs invoked from the current program.
The expr command evaluates its arguments as an expression. It’s most commonly used for simple arithmetic in the following form:
x=`expr $x + 1`
The `` (backtick) characters make x take the result of executing the command expr $x + 1. You could also write it using the syntax $( ) rather than backticks, like this:
x=$(expr $x + 1)
(18) return
(19) set
The set command sets the parameter variables for the shell. It can be a useful way of using fields in commands that output space-separated values.
#!/bin/sh
echo the date is $(date)
set $(date)
echo The month is $2
exit 0
The shift command moves all the parameter variables down by one, so that $2 becomes $1, $3 becomes $2, and so on. The previous value of $1 is discarded, while $0 remains unchanged. If a numerical parameter is specified in the call to shift, the parameters move that many spaces. The other variables, $*, $@, and $#, are also modified in line with the new arrangement of parameter variables.
The trap command is passed the action to take, followed by the signal name (or names) to trap on:
几个月来,自从手动装上Firefox3.0之后,在Fedora桌面上点击图标启动Firefox一直进入www.s.com(本来我的主页设置为iGoogle),而且图标也不再显示为Firefox的图标。很是让人郁闷。(注:据说该问题只是在图形界面下点击图标才会出现,若在命令行下面直接用命令启动Firefox不会有这个问题。)
今天搜了一下,发现有这个问题的人还比较多,但大多没有解决方法。找了半天之后总算发现有人给出了方法。原来问题出自 ~/.local/share/applications/preferred-web-browser.desktop 中的Exec选项。
手动装完Firefox之后把我的preferred-web-browser.desktop中的Exec改成了
Exec=/opt/firefox/firefox "%s"
由于我是在我的个人用户下装的Firefox 3,因此root用户并没有受到影响,root用户的preferred-web-browser.desktop也没有被该变。于是我参照root用户的配置把Exec改成了
Exec=/opt/firefox/firefox %u
同时把Icon选项改成了 Icon=firefox
把Name改为 Name=Firefox Web Browser
再重新启动Firefox,一切正常!
3 基本的Shell命令
3.1 Redirecting Output
管道重定向:>
对文件追加:>>
For
">", by default, if the file already exists, then it will be
overwritten. If you want to change the default behavior, you can use
the command set -o noclobber (or set -C), which sets the noclobber option to prevent a file from being overwritten using redirection. You can cancel this option using set +o noclobber.
For ">>", outputs are appended to the end of the file.
File descriptor 0 is the standard input to a program, file descriptor 1
is the standard output, and file descriptor 2 is the standard error
output. It’s unusual to want to redirect any other than the standard
ones: 0, 1, and 2.
To redirect the
standard error output, preface the > operator with the number of the
file descriptor you wish to redirect. Because the standard error is on
file descriptor 2, use the 2> operator. This is often useful to
discard error information and prevent it from appearing on the screen.
The command
$ kill -HUP 1234 >killout.txt 2>killerr.txt
will put the output and error information into separate files.
If you prefer to capture both sets of output into a single file, you can use the >& operator to combine the two outputs. Therefore,
$ kill -1 1234 >killouterr.txt 2>&1
will
put both the output and error outputs into the same file. Notice the
order of the operators. This reads as “redirect standard output to the
file killouterr.txt, and then direct standard error to the same place
as the standard output.” If you get the order wrong, the redirect won’t
work as you expect.
3.2 Redirecting Input
<
3.3 Pipes
Processes connected by pipes can run simultaneously and are automatically rescheduled as data flows between them.
3.4 file command
The best way to check if a file is a script or not is to use the file command — for example, file first or file /bin/bash.
3.5 read command
Check which command is used, e.g. which test.
3.7 touch filename
Check whether it exists and create it if it doesn’t.
4.3 Parameter Variables
If
your script is invoked with parameters, some additional variables are created. If no parameters are passed, the environment variable $# still exists but has a value of 0.
Remember
that adding the quotes tells the shell to consider everything between
them as a single string. This is one way of getting spaces to be stored
in a variable.
4.5 The test or [ Command
for variable in values
do
statements
done
Note:
for file in $(ls f*.sh); do
In this example, the parameter list for the for command is provided by the output of the command enclosed in the $() sequence.
(3)
while condition do
statements
done
(4)
until condition
do
statements
done
Note: In general, if a loop should always execute at least once, use a while loop; if it may not need to execute at all, use an until loop.
(5)
case variable in
pattern [ | pattern] ...) statements;;
pattern [ | pattern] ...) statements;;
...
esac
Note:
(6) Lists
(7) Statement Blocks
If you want to use multiple statements in a place
where only one is allowed, such as in an AND or OR list, you can do so
by enclosing them in braces {} to make a statement block.
(8) Shell Function
function_name () {
statements
}