Tcl/Tk Notes (3)

Part III Tcl Data Structures

1 More about Variables

  • The set command

        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.

    In the last command, $name gets substituted with var. Then the set command returns the value of var, which is the value of var. Another way to achieve a level of indirection like this is with nested set commands. The last set command above can be written as follows:
        set [set name]
        => the value of var

  • The unset command 

    You can delete a variable with the unset command:
        unset varName varName2 ...

  • Using info to find out about variables

    The existence of a variable can be tested with the info exists command.
        if ![info exists foobar]{
            set foobar 0
        } else {
            incr foobar }

2 Tcl Lists

    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.

3 Constructing Lists: list, lappend and concat

    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.
            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.

4 Getting List Elements: llength, lindex, and lrange

    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.
            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.
            lrange {1 2 3 {4 5}} 2 end
            => 3 {4 5}

5 Modifying Lists: linsert and lreplace

    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.
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
            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

6 Searching Lists: lsearch

    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.
        proc delete {list value} {
            set ix [lsearch -exact $list $value]
            if {$ix>=0} {
                return [lreplace $list $ix $ix]
            } else {
                return $list

7 Sorting List: lsort

    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.

8 The split And join Commands

    The split command
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

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:

    The join command
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

    The index of an array is delimited by parentheses. The
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.}
the array index is stored in a variable, then there is no problem with
spaces in the variable's value. The following works fine:
            set index {
I'm asking for trouble}
            set arr($index) {
I told you so.}
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

    The array names command is perhaps the most useful because it allows easy iteration through an array with a foreach loop:
            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

    In UNIX, the process environment variables are available through the global array env.
The name of the environment variable is the index,e.g. env(PATH), and
the array element contains the current value of the environment

12 Tracing Variable Values

    The trace command lets you register a command to be called whenever a variable is accessed, modified or unset. The form is:
        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

    Information about traces on a varible is returned with the vinfo option.
        trace vinfo dynamic
        => {r FixDynamic}
    A trace is deleted with the vdelete trace option, which has the same form as the varible option.

Tcl/Tk Notes (1)

Tcl/Tk Notes

Part I TCL Overview

1 Everything Is a String

    In Tcl, evrything is a string, and you have to explicitly ask for evaluation of variables and nested commands.

2 Substitution

  • Variable
    The use of dollar sign($) is one kind of substitution. Variables can be assigned values by set command.

  • Command Substitution
    A nested command is delimited by square brackets, [ and ]. The Tcl
takes everything between the brackets and evaluates it as a command. It
Reqrites the outer command by replacing the square brackets and
everything between them with the result of nested command.

  • Math Expression
    The expr command is used to evaluate math expressions. The Tcl interpreter treats expr just like any other command, and it leaves the expression parsing up to the expr implementation.

  • Backslash Substitution

    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.

3 Double Quotes vs. Curly Braces

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

In practice, grouping with curly braces is used when substitutions on
the argument need to be delayed until a later time( or never done at
all). Examples include contrl flow statements and procedure
declararions. Double quotes are usefulin simple cases like the puts command.

    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
    e.g. puts [format "Item: %s/t%5.3f" $name $value]

4 Procedures

    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

5 A While Loop Example

    The loop around boolean expression $i<=10
is crucial, because it delays substitution until while command
implementation tests the expression. The following expression is an
infinite loop:
        set i; while $i<=10 {incr i}
    The Tcl interpreter will substitute for $i before while is called, so while gets a constant expression 1<=10
that will always be ture.You can avoid this kind of errors by adopting
a consistent coding style that always groups expressions and command
bodies with curly braces.
    The command in the example uses set with a single argument. When used in this way the set command returns the current value of the named variable.

6 Grouping And Command Substitution

decisions are made before substitutions are performed. This means that
the values of variables or command results do not affect grouping.
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.


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.

8 Reference

  • backslash Sequences

  • Arithmetic Operators
  • Built-in Math Function
  • Core Tcl Commands

  • Predefined Variables

UNIX Workshop Notes

st1/:*{behavior:url(#ieooui) }

UNIX Workshop Notes

1 The
UNIX Philosophy

  • small
    is beautiful
  • make
    each program do one thing well
  • build
    a prototype as soon as possible
  • choose
    portability over efficiency
  • store
    numerical data in flat files
  • use
    software leverage to your advantage
  • use
    shell scripts to increase leverage and portability
  • avoid
    captive user interfaces
  • make
    every program a filter


The Ten Lesser Tenets

  • allow
    the user to tailor the environment
  • make
    operating system kernels small and lightweight
  • use
    lower case and keep it short
  • save
  • silence
    is golden
  • think
  • the
    sum of the parts if greater than the whole
  • look
    for the ninety percent solution
  • worse
    is better
  • think


2 /etc/passwd

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.


3 init process

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.


4 Address Space

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.


5 Process

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.


Process status:

R - runable, currently on the run

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)



SIGHUP       1          Hangup

SIGINT        2          Interrupt

SIGKILL      9          Kill (cannot be
caught or ignore)

SIGTERM    15        Terminate
(termination signal from SIGKILL)


6 Boot and Shutdown UNIX

(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

( !!! may damage system )

( good way )

 halt (
will change system to single user mode )


 init or
telinit ( change the run level )


7 su V.S. su -

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



8 Unix Environment

setup user environment in ksh


shell variables: varname=value

unset variables



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.

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

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.


Built-in Variables

  • PS1,
    PS2, PS3 , PS4
  • TERM
  • PATH,
  • HOME
  • PWD


9 Common Control Characters

Erase Character


 [DELETE], [DEL] key


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.


10 File System Inside

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.


11 I/O Redirection

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.


grep for pattern in all files on
the home directory /home/foo:

find /home/foo -print | xargs grep pattern > out &

12 Search and Patterns

(1) Searching Commands

… find

… grep

… egrep

… fgrep

find pathname(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

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.

13 UNIX Power Tools

(1) Backup & Compression









filename suffix

. .tar

. .Z

. .gz

. .tar.Z

. .tar.gz

. .zip

. .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

awk              Use the pattern-matching program to modify the
specified files


(3) Job Control







(4) Communication and network

















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 单引号字符串
6 双引号字符串
| 符号    | 含义                                    |
| /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 数字和字符串之间的自动转换

9 Perl中的标量变量都形如$fred。当一个字符串由双引号括起来时,如果变量前没有反斜线,则变量的值会被替换(如果一个变量未被赋值,则将使用空值)。Perl提供了分隔符{}将变量名括起来,如:
    $what="brontosaurus steak";
    print "fred ate $n $whats./n";        #输出不是steaks,而是$whats的值
    print "fred ate $n ${what}s./n";    #现在使用$what的值。

10 Perl中没有Boolean类型,但可以利用一下几条法则帮助记忆:

11 行输入运算符:<STDIN>。<STDIN>作为标量值来使用,Perl每次在标准输入中读入文本下一行,将其传给<STDIN>。利用<STDIN>读入的字符串行尾是有换行符的,可以利用chomp函数来去掉。chomp是一个函数,作为函数它有一个返回值,为移除的字符的个数。在使用chomp时,可以使用或不使用(),这又是perl中的一条通用规则:除非移除它们会改变含义,否则括号是可以省略的。如果结尾有两个或两个以上的换行符,chomp仅去掉一个。

12 undef值

13 defined函数


~/.profile 是在用户的主目录下的一个文件,每次用户登陆都会执行这里边的ENV环境变量设置。

如果想让刚刚改变的.profile .kshrc里面的设置马上生效使用,可以使用以下的命令:
                . ~/.profile
                . ~/.kshrc

[转]C++ 运算符优先级列表

C++ 运算符优先级列表 
Precedence Operator Description Example Associativity
1 ()
Grouping operator
Array access
Member access from a pointer
Member access from an object
Scoping operator
(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 !
Logical negation
Bitwise complement
Unary minus
Unary plus
Address of
Cast to a given type
Return size in bytes
if( !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 selector
ptr->*var = 24;
obj.*var = 24;
left to right
4 *
int i = 2 * 4;
float f = 10 / 3;
int rem = 4 % 3;
left to right
5 +
int i = 2 + 3;
int i = 5 - 1;
left to right
6 <<
Bitwise shift left
Bitwise shift right
int 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-to
if( i < 42 ) ...
if( i <= 42 ) ...
if( i > 42 ) ...
if( i >= 42 ) ...
left to right
8 ==
Comparison equal-to
Comparison not-equal-to
if( 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 assign
int 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

《Beiginning Linux programming || Linux 程序设计》读书笔记(四)

(21) Trap

    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:

        trap command signal
that the scripts are normally interpreted from top to bottom, so you
must specify the trap command before the part of the script you wish to

    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 /.

    $ 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:
         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.


while [ "$x" -ne 10 ]; do
    echo $x

exit 0

(28) Parameter Expansion

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.


unset foo
echo ${foo:-bar}

echo ${foo:-bar}

echo ${foo#*/}
echo ${foo##*/}

echo ${bar%local*}
echo ${bar%%local*}

exit 0

The output is:


(29) Here Document
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.


cat <<!FUNKY!
this is a here


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

# 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

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
  dialog --title "Doesn’t like Classical" --msgbox "Shame" 12 25

sleep 2
dialog --clear
exit 0

    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.

《Beiginning Linux programming || Linux 程序设计》读书笔记(三)

(8) Shell Function
    function_name () {
    You must always define a function before you can invoke it.When a function is invoked, the positional parameters to the script, $*, $@, $#, $1, $2, and so on, are replaced by the parameters to the function.When the function finishes, they are restored to their previous values.
    You can make functions return numeric values using the return command. The usual way to make functions return strings is for the function to store the string in a variable, which can then be used after the function finishes. Alternatively, you can echo a string and catch the result, like this:
        foo () { echo JAY;}
    You can declare local variables within shell functions by using the local keyword. The variable is then only in scope within the function.

(9) break

(10) The : Command
    The colon command is an alias for true.
    The : construct is also useful in the conditional setting of variables. For example,
        : ${var:=value}
Without the :, the shell would try to evaluate $var as a command.

(11) Continue

(12) The . Command
(13) eval
    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.

(14) exec
    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.

(15) export
    The export command creates an environment variable from its parameter that can be seen by other scripts and programs invoked from the current program. 

(16) expr
    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)

(17) printf
(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.

        echo the date is $(date)
        set $(date)
        echo The month is $2

        exit 0

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
    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.

(21) Trap
    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:
        trap command signal
Remember that the scripts are normally interpreted from top to bottom, so you must specify the trap command before the part of the script you wish to protect.

Fedora 9中Firefox启动后进入www.s.com的解决方法


今天搜了一下,发现有这个问题的人还比较多,但大多没有解决方法。找了半天之后总算发现有人给出了方法。原来问题出自 ~/.local/share/applications/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


《Beginning Linux Programming》读书笔记(二)

 3 基本的Shell命令
3.1 Redirecting Output
">", 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
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

    You can assign user input to a variable by using the read command.The read normally completes when the user presses Enter.
3.6 which

    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 Shell Scripts
4.1 Quoting
 If you enclose a $ variable expression in double quotes, then it’s
replaced with its value when the line is executed. If you enclose it in
single quotes, then no substitution takes place. You can also remove
the special meaning of the $ symbol by prefacing it with a /.
 Usually, strings are enclosed in double quotes, which protects
variables from being separated by whitespace but allows $ expansion to
take place.
4.2 Environment Variables
    If you want to check out how the program works in a different environment by running the env <command>, try looking at the env manual pages.

4.3 Parameter Variables
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.

As you can see, within double quotes, $@ expands the positional parameters as separate fields, regardless of the IFS value. In general, if you want access to the parameters, $@ is the sensible choice.

4.4 A Problem With Variables
     For a script
        if [ $timeofday = “yes” ]
, if just press "Enter",rather than answer anything.When the variable timeofday was tested, it consisted of a blank string. Therefore, the if clause looks like
        if [ = “yes” ]
which isn't a valid condition. To avoid this, you must use quotes around the variable:
        if [ “$timeofday” = “yes” ]
An empty variable then gives the valid test:
        if [ “” = “yes” ]

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

    The [ and test commands are synonymous, except that when the [ command is used, a trailing ] is also used. The test or [ can be used to check to see whether a file exists.
e.g.    test -f <filename> or [ -f <filename> ]
    (Note: You must put spaces between the [ braces and the condition being checked.)
    Conditions that you can use test command are:
4.6 Control Structures
        if condition
        elif condition; then


    for variable in values

        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.

    while condition do

    until condition

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.


    case variable in
        pattern [ | pattern] ...) statements;;
        pattern [ | pattern] ...) statements;;


  •     Notice
    that each pattern line is terminated with double semicolons (;;). You
    can put multiple statements between each pattern and the next, so a
    double semicolon is needed to mark where one statement ends and the
    next pattern begins.

  •     Be
    careful with the case construct if you are using wildcards such as ‘*‘
    in the pattern. The problem is that the first matching pattern will be
    taken, even if a later pattern matches more exactly.

(6) Lists

  •     AND
    List: The AND list construct enables you to execute a series of
    commands, executing the next command only if all the previous commands
    have succeeded. The syntax is
          statement1 && statement2 && statement3 && ...
  •     OR
    List: The OR list construct enables us to execute a series of commands
    until one succeeds, and then not execute any more. The syntax is as
        statement1 || statement2 || statement3 || ...

(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 () {