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


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

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

    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.

7 Comments

    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.

8 Reference

  • backslash Sequences

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

  • Predefined Variables

UNIX Workshop Notes

<style>
st1/:*{behavior:url(#ieooui) }
</style>
<![endif]-->

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
    trees
  • silence
    is golden
  • think
    parallel
  • the
    sum of the parts if greater than the whole
  • look
    for the ninety percent solution
  • worse
    is better
  • think
    hierarchically

 

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

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)

 

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

·       
 Poweroff
( !!! may damage system )

·       
 Shutdown
( good way )

·       
 halt (
will change system to single user mode )

·       
 reboot

·       
 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

superuser(root).

 

8 Unix Environment

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

  • PS1,
    PS2, PS3 , PS4
  • TERM
  • PATH,
    MANPATH
  • HOME
  • PWD
  • HISTFILE
  • EDITOR
  • VISUAL

 

9 Common Control Characters

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.

 

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.

Example:

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

13 UNIX Power Tools

(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

 

 

 

 

 

 

Perl笔记(一)

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函数

Solaris环境变量

~/.profile 是在用户的主目录下的一个文件,每次用户登陆都会执行这里边的ENV环境变量设置。
/etc/profile是一个全局的环境变量设置,只要登陆系统的用户都会执行里面的ENV环境变量设置
~/.kshrc是在用户的主目录下面的,每次执行KSH下面的子shell的时候,都会执行这里面的ENV环境变量设置。
~/.dtprofile是在用户的主目录下面的,在这里设置你进入CDE时的一些变量设置,如果用户没有通过CDE进入过系统,那么将不会产生这个文件,只有用户曾经用CDE进入过系统后就会自动生成一个.dtprofile文件,然后还可以对里边的变量进行设置。。
                如果在这个文件里的DTSOURCEPROFILE的变量设置为true则会读取用户瞩目路下的.profile文件里的变量设置,如果没有这个变量或者设置为false,那么将不读取.profile里的环境变量。

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

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


C++ 运算符优先级列表

http://www.cppreference.com/operator_precedence.html 
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)
sizeof
Logical negation
Bitwise complement
Pre-increment
Pre-decrement
Unary minus
Unary plus
Dereference
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 *
/
%
Multiplication
Division
Modulus
int i = 2 * 4;
float f = 10 / 3;
int rem = 4 % 3;
left to right
5 +
-
Addition
Subtraction
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
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.

    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.

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

(8) Shell Function
    function_name () {
        statements
    }
    
    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;}
            ...
        result=”$(foo)“
    
    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.
        #!/bin/sh

        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的解决方法

几个月来,自从手动装上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,一切正常!

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

 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

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

   
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” ]

    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

    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
(1)
        if condition
        then
            statements
        elif condition; then
        else
            statements
        fi

(2)

    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:

  •     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
    follows:
        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 () {

        statements

    }

《Linux程序设计》读书笔记(一)

 

《Linux程序设计》读书笔记


1、编译C程序的技巧

    在调用C语言编译器的时候可以通过给出“-I”标志来引用保存在下级子目录或者非标准目录下的头文件,如:
        $ gcc -I /usr/openwin/include fred.c
它会使编译器在/usr/openwin/include的子目录和标准目录两个地方去查找fred.c程序里所包含的头文件。

    用grep查找含有某些特定定义与函数生命的头文件是很方便的。如:
        $ grep EXIT_ *.h
grep命令会在该子目录下的所有名字以.h结尾的文件里查找字符串“EXIT_”。

2、库文件
   
标准的系统库文件一般保存在/lib或/usr/lib子目录中。库文件的名字永远以“lib”这几个字母打头,随后便是函数库说明的部分(比如用c表示
这是一个C语言函数库,用m表示一个数学运算库),文件名的最后部分以一个“.”开始,然后给出这个库文件的类型:静态函数库.a;共享函数库.so
或.sa。
    在通知编译器查找某个库文件的时候,既可以给出其完整的路径名,也可以使用“-l”标志,。如:
        $ cc -o fred fred.c /usr/lib/libm.a

        $ cc -o fred fred.c -lm
-lm代表标准目录库中名为libm.a的函数库。 更详细的解释参见下面的例子。
    虽然库文件与头文件相似,都是被保存在某个标准位置,但我们仍然可以通过“-L”标志给编译器增加搜索子目录库。如:
        $ cc -o x11fred -L/usr/openwin/lib x11fred.c -lX11
该命令在编译和链接程序x11fred时将使用在子目录/usr/openwin/lib中找到的libX11函数库版本。

    2.1 静态库(archive)
    假设现有源文件bill.c和fred.c,则建立静态库的方法:
    (1)编译源文件生成二进制目标文件,需要在调用C编译器时加上“-c”选项以防止生成最终应用程序。
        $ cc -c bill.c fred.c
    (2)为函数库建立一个头文件(lib.h),它的作用是在我们的函数库里对这两个函数进行声明;如果有程序要使用这个函数库,就必须使用include引用。
    (3)调用程序(program.c)引用库函数头文件并调用其中的函数。
    (4)使用ar工具简历档案并把目标代码加入其中。
        $ ar crv libfoo.a bill.o fred.o
  
    另外,某些系统(尤其是Berkley UNIX操作系统发展而来的系统)上,要想成功是用函数库,必须先为这个函数库建立一个内容表:
        $ ranlib libfoo.a

    可以通过使用“-L”选项告诉编译器静态库的位置:
        $ cc -o program program.o -L. -lfoo
“-L.”告诉编译器在当前子目录中查找函数库。“-lfoo”选项告诉编译器使用那个名为libfoo.a的函数库(或者一个名为libfoo.so的共享库,如果有的话)。

    可以使用nm命令查看某个目标代码文件、函数库或者可执行程序里都包含那些函数。

    2.2 共享库
   
如果一个程序使用了共享库,它的连接方式是这样的:它本身不再保存函数的代码,而只保存共享代码的调用线索,共享代码是在运行的时候才加入其中的。对
Linux系统而言,负责加载共享库并解析客户程序中函数调用线索的程序(即共享库动态加载器)是ld.so或ld-linux.so.2;查找共享库的
其他地点是在/etc/ld.so.conf文件里配置的;如果这个文件进行了修改,就需要用ldconfig命令进行处理。
    可以使用ldd程序查看某个程序要求使用的是哪一个共享库:
        $ ldd program

    .so类似于Windows中的.DLL文件,是运行时加入程序的;.sa类似于Windows中的.LIB文件,是加入到可执行文件里面的。

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.

4 Shell Scripts

P60, to be continued...