Advanced Bash-Scripting Guide 开始至第三章

2010年12月20日 星期一
Revision 6.2 17 Mar 2010 Revised by: mc
'ROWANBERRY' release

下载地址: http://www.tldp.org/LDP/abs/
含单独脚本源文件: http://bash.webofcrafts.net/abs-guide-latest.tar.bz2
脚本源文件名可在 /abs-guide/index.html 后面的 List of Examples中查找,如:/abs-guide/othertypesv.html 中 Example 4-5. Positional Parameters,它的链接为:/abs-guide/othertypesv.html#EX17 它的脚本文件名即为:ex17.sh 加上可执行属性就可直接执行验证
Continue reading "Advanced Bash-Scripting Guide 开始至第三章"

开始学习 Dvdwizard 源码

时不我待,本来准备继续学习 BLFS ,为做一个针对手机影音转换的系统做准备。可是,我做的东西应该是以应用层为主,这种系统层面的东西有个基本的掌握就行了,以后确有必要的时候再定制一个系统。现在计划先把这个应用工具完成一个原型再说,准备用 bash 脚本调用各种工具实现,再在此基础上弄一个图形界面(easybashgui(https://sites.google.com/site/easybashgui))。然后把这个工具集成到一个已有的微型 LiveCD 发行版中(如: Tinycore)。如果有必要,如图形界面无法商业化的应用,那么就真的要学点 Gtk 编程的东西。好在我对编程并不是很陌生,花点时间应该很快上手。现在问题是,我的 bash 脚本编程知识非常基础,没有系统的学习过,而要从头系统的找一本书来学又太漫长了,于是,就准备找一个现成的 Bash 实例来深入学习一下 Bash 编程。
Continue reading "开始学习 Dvdwizard 源码"

9.2. Manipulating Strings

9.2. Manipulating Strings

1、String Length

expr "$string" : '.*'

3、Index这个表达式跟java的用法好像不同

expr index $string $substring

    Numerical position in $string of first character in $substring that matches.


   5 echo `expr index "$stringZ" 1c`              # 3

   6 # 'c' (in #3 position) matches before '1'.

4?{string:position:length}负数参数的用法有点怪

    Extracts $length characters of substring from $string at $position.


  16 echo ${stringZ:-4}                           # abcABC123ABCabc

  17 # Defaults to full string, as in ${parameter:-default}.

  18 # However . . .

  19

  20 echo ${stringZ:(-4)}                         # Cabc

  21 echo ${stringZ: -4}                          # Cabc

  22 # Now, it works.

  23 # Parentheses or added space "escape" the position parameter.

  24

  25 # Thank you, Dan Jacobson, for pointing this out.

而且下面这段不懂:


    If the $string parameter is "*" or "@", then this extracts a maximum of

$length positional parameters, starting at $position.

       1 echo ${*:2}          # Echoes second and following positional

parameters.

       2 echo ${@:2}          # Same as above.

       3

       4 echo ${*:2:3}        # Echoes three positional parameters, starting

at second.

5、Example 9-12. Emulating getopt其中的字符串处理不甚明了


  14       if [ ${1:0:1} = '/' ]

  15       then

  16           tmp=${1:1}               # Strip off leading '/' . . .

  17           parameter=${tmp%%=*}     # Extract name.

  18           value=${tmp##*=}         # Extract value.

  19           echo "Parameter: '$parameter', value: '$value'"

  20           eval $parameter=$value

  21       fi

6、awk处理函数不懂


  14 # The awk equivalent of ${string:pos:length} is

substr(string,pos,length).

  15 echo | awk '

  16 { print substr("'"${String}"'",3,4)      # skid

  17 }

  18 '

7、9.2.2. Further Discussion进一步讨论的几个例子没看

英语疑问:

1、emulation, getopt

A simple emulation of getopt  using substring extraction constructs.

9.1. Internal Variables

9.1. Internal Variables

1、不懂:


$DIRSTACK

    the top value in the directory stack (affected by pushd and popd)

    This builtin variable corresponds to the dirs command, however dirs shows

    the entire contents of the directory stack.

2、

 


$EUID

    "effective" user ID number

    Identification number of whatever identity the current user has assumed,

    perhaps by means of su.

    Caution The $EUID is not necessarily the same as the $UID.

3、


  $GLOBIGNORE

    A list of filename patterns to be excluded from matching in globbing.

4、


     root# echo ${GROUPS[1]}

     1

5、


    $IFS defaults to whitespace (space, tab, and newline), but may be changed,

    for example, to parse a comma-separated data file. Note that $* uses the

    first character held in $IFS. See Example 5-1.

     bash$ echo $IFS | cat -vte

     $

     bash$ bash -c 'set w x y z; IFS=":-;"; echo "$*"'

     w:x:y:z

6、IFS是空格时,字符间的多个空格视为一个分隔符,第一个字符前面的空格会忽略不计。见例子ifs.sh。


              14 IFS=" "

              15 var=" a  b c   "

 ...

              26 IFS=:

              27 var=":a::b:c:::"               # Same as above, but substitute

运行结果:


[mdx@localhost abs-exercises]$ ./ex9-1.sh

IFS=" "

-------

the arg is: [a]

the arg is: [b]

the arg is: [c]

IFS=:

-----

the arg is: []

the arg is: [a]

the arg is: []

the arg is: [b]

the arg is: [c]

the arg is: []

the arg is: []

[mdx@localhost abs-exercises]$

7、$LINENO 不懂


$LINENO

    This variable is the line number of the shell script in which this

variable

    appears. It has significance only within the script in which it appears,

    and is chiefly useful for debugging purposes.

       1 # *** BEGIN DEBUG BLOCK ***

       2 last_cmd_arg=$_  # Save it.

       3

       4 echo "At line number $LINENO, variable \"v1\" = $v1"

       5 echo "Last command argument processed = $last_cmd_arg"

       6 # *** END DEBUG BLOCK ***

8、$PIPESTATUS不懂,并且在本机上的执行结果与书中的不同


     bash$ echo $PIPESTATUS

     0

     bash$ ls -al | bogus_command

     bash: bogus_command: command not found

     bash$ echo $PIPESTATUS

     141

     bash$ ls -al | bogus_command

     bash: bogus_command: command not found

     bash$ echo $?

     127

...

          bash$ echo ${PIPESTATUS[@]}

9、不懂

$PWD的:


      22 # rm -f .[^.]* ..?*   to remove filenames beginning with multiple

dots.      23 # (shopt -s dotglob; rm -f *)   will also work.

      24 # Thanks, S.C. for pointing this out.

10、不懂$SHELLOPTS的用法


[mdx@localhost abs-exercises]$ echo $SHELLOPTS

braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor

11、$SHLVL的用法


$SHLVL

    Shell level, how deeply Bash is nested. If, at the command line, $SHLVL is

    1, then in a script it will increment to 2.

12、$TMOUT的用法不懂,例子example9-2~9-4不懂

13、$UID,下面这段话的意思不懂

This is the current user's real id, even if she has temporarily assumed

    another identity through su.

14、example9-7太复杂了,留在这里备忘


    Caution The $* and $@ parameters sometimes display inconsistent and

            puzzling behavior, depending on the setting of $IFS.

    ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

    Example 9-7. Inconsistent $* and $@ behavior

15、set命令的用法


[mdx@localhost abs-exercises]$ set a b c

[mdx@localhost abs-exercises]$ echo $1 $2 $3

a b c

[mdx@localhost abs-exercises]$

16、$!的用法

书上的例子:

LOG=$0.log

COMMAND1="sleep 100"

echo "Logging PIDs background commands for script: $0" >> "$LOG"

# So they can be monitored, and killed as necessary.

echo >> "$LOG"

# Logging commands.

echo -n "PID of \"$COMMAND1\":  " >> "$LOG"

${COMMAND1} &

echo $! >> "$LOG"

# PID of "sleep 100":  1506

# Thank you, Jacques Lederer, for suggesting this.

#下面这句不大懂:eval, kill -9

#possibly_hanging_job & { sleep ${TIMEOUT}; eval 'kill -9 $!' &> /dev/null; }      

# Forces completion of an ill-behaved program.

# Useful, for example, in init scripts.

# Thank you, Sylvain Fourmanoit, for this creative use of the "!" varia

英语疑问:

1、subtleties, nuances

This requires learning their subtleties and nuances.

2、necessarily

$SHELL does not necessarily give the correct answer.

3、collation order, mishandled

$LC_COLLATE

    Often set in the .bashrc or /etc/profile files, this variable controls

    collation order in filename expansion and pattern matching. If mishandled,

    LC_COLLATE can cause unexpected results in filename globbing.

4、revert, customary

To revert to the customary behavior of bracket matching, set LC_COLLATE to C by an export LC_COLLATE=C in /etc/profile and/or ~/.bashrc.

5、expedient

In a script, it may be expedient to temporarily add a directory to the path

    in this way.

6、likewise

         $SHELL, the name of the user's login shell, may be set from /

         etc/passwd or in an "init" script, and it is likewise not a

         Bash builtin.

8.2. Numerical Constants

8.2. Numerical Constants

1、Example 8-4. Representation of numerical constants

同C语言一样,字符也是整数。但是@和_代表是多少不知道?而且把它们转化为十进制的方法忘记了。

  32 let "b64 = 64#@_"

  33 echo "base-64 number = $b64"             # 4031

  34 # This notation only works for a limited range (2 - 64) of ASCII characters  35 # 10 digits + 26 lowercase characters + 26 uppercase characters + @ + _

  36

  37

  38 echo

  39

  40 echo $((36#zz)) $((2#10101010)) $((16#AF16)) $((53#1aA))

  41                                          # 1295 170 44822 3375

英语疑难: evaluates

A number with an embedded # evaluates as BASE#NUMBER (with range and notational restrictions).

8.1. Operators

Chapter 8. Operations and Related Topics

8.1. Operators

1、Example 8-1. Greatest common divisor最大公约数的算法不懂,里面的练习:判断命令行参数是否是整数不懂,记在这里。

2、发现一个问题,bash的算术操作符只能进行整数的运算,要进行其它的复杂点的运算:如开方、小数等怎么办呢?

3、Example 8-2. Using Arithmetic Operations

这个例子有不少地方不明白,记在这里以后进一步解决:

我知道 let "z = 2 + 3" 相当于 (( z = 2 + 3 )),根据:


Similar to the let command, the ((...)) construct permits arithmetic expansion

and evaluation.

1)、


      10 : $((n = $n + 1))

      11 #  ":" necessary because otherwise Bash attempts

      12 #+ to interpret "$((n = $n + 1))" as a command.

2)、      20 n=$(($n + 1))

3)、

      23 : $[ n = $n + 1 ]

      24 #  ":" necessary because otherwise Bash attempts

      25 #+ to interpret "$[ n = $n + 1 ]" as a command.

      26 #  Works even if "n" was initialized as a string.

4)、

      29 n=$[ $n + 1 ]

      30 #  Works even if "n" was initialized as a string.

      31 #* Avoid this type of construct, since it is obsolete and

nonportable.

      32 #  Thanks, Stephane Chazelas.

5)、      44 : $(( n++ ))       # : $(( ++n )) also works.

6)、      47 : $[ n++ ]         # : $[ ++n ]] also works

4、bash不能处理浮点数:


Bash does not understand floating point arithmetic. It treats numbers containing a decimal point as strings.

5、

if [ $condition1 -a $condition2 ] 相当于 if [[ $condition1 && $condition2 ]]

,但是&&不能用在[...]结构中,这些有什么规律吗?真不好掌握啊。

6、Example 8-3. Compound Condition Tests Using && and ||


6 if [ "$a" -eq 24 ] && [ "$b" -eq 47 ]

17 #  Note:  if [[ $a -eq 24 && $b -eq 24 ]]  works.

20 #    (The "&&" has a different meaning in line 17 than in line 6.)

我不懂&&在6行和17行有什么区别?

7、不懂 $((...))的用法


     bash$ echo $(( 1 && 2 )) $((3 && 0)) $((4 || 0)) $((0 || 0))

     1 0 1 0

英语疑问:

1、Modulo turns up surprisingly often in various numerical recipes.

2、erroneous

An operation that takes a variable outside these limits will give an erroneous result.

3、flip, relevant, fly

"Bit flipping" is more relevant to compiled languages, such

as C and C++, which run fast enough to permit its use on the fly.

4、miscellaneous operators

5、evaluated

All the operations are evaluated (with possible side effects), but only the last operation is returned.