5.2. Escaping

1、Example 5-2(怎么样才能显示下面这个 $escape ?)

 


      54 escape=$'\033'                    # 033 is octal for escape.

      55 echo "\"escape\" echoes as $escape"

      56 #                                   no visible output.

 

2、echo -e的用法:


[mdx@localhost abs-exercises]$ echo "\n"

\n

[mdx@localhost abs-exercises]$ echo -e "\n"

[mdx@localhost abs-exercises]$

[mdx@localhost abs-exercises]$ echo "\\"

\

[mdx@localhost abs-exercises]$ echo -e "\\"

\

[mdx@localhost abs-exercises]$ echo -e '\\'

\

[mdx@localhost abs-exercises]$ echo  '\\'

\\

3、可是说是一些非常烦人的用法,不用去记它,平常也用不着吧。

Note The behavior of \ depends on whether it is itself escaped, quoted, or

     appearing within command substitution or a here document.


        1                       #  Simple escaping and quoting

        2 echo \z               #  z

        3 echo \\z              # \z

        4 echo '\z'             # \z

        5 echo '\\z'            # \\z

        6 echo "\z"             # \z

        7 echo "\\z"            # \z

        8

        9                       #  Command substitution

       10 echo `echo \z`        #  z

       11 echo `echo \\z`       #  z

       12 echo `echo \\\z`      # \z

       13 echo `echo \\\\z`     # \z

       14 echo `echo \\\\\\z`   # \z

       15 echo `echo \\\\\\\z`  # \\z

       16 echo `echo "\z"`      # \z

       17 echo `echo "\\z"`     # \z

       18

       19                       # Here document

       20 cat <<EOF

       21 \z

       22 EOF                   # \z

       23

       24 cat <<EOF

       25 \\z

       26 EOF                   # \z

       27

       28 # These examples supplied by St?phane Chazelas.

4、\可以起到续行符的作用,文中的叙述:

The escape also provides a means of writing a multi-line command. Normally,

each separate line constitutes a different command, but an escape at the end of

a line escapes the newline character, and the command sequence continues on to

the next line.

例如:下面的dir这个命令被分成3行来写,每行一个字符:)


[mdx@localhost abs-exercises]$ d\

> i\

> r

ch4-2.txt  ctrl-h.sh  ex2-1.sh  ex2-3.sh  ex4-5.sh  ex4-7.sh  plan2.txt

ch5-2.txt  ctrl-m.sh  ex2-2.sh  ex4-2.sh  ex4-6.sh  ex5-2.sh  plan.txt

[mdx@localhost abs-exercises]$ dir

ch4-2.txt  ctrl-h.sh  ex2-1.sh  ex2-3.sh  ex4-5.sh  ex4-7.sh  plan2.txt

ch5-2.txt  ctrl-m.sh  ex2-2.sh  ex4-2.sh  ex4-6.sh  ex5-2.sh  plan.txt

Chapter 5. Quoting

Chapter 5. Quoting

1、那个IFS是什么意思?

Example 5-1. Echoing Weird Variables


   1 #!/bin/bash

   2 # weirdvars.sh: Echoing weird variables.

   3

   4 var="'(]\\{}\$\""

   5 echo $var        # '(]\{}$"

   6 echo "$var"      # '(]\{}$"     Doesn't make a difference.

   7

   8 echo

   9

  10 IFS='\'

  11 echo $var        # '(] {}$"     \ converted to space. Why?

  12 echo "$var"      # '(]\{}$"

  13

  14 # Examples above supplied by Stephane Chazelas.

  15

  16 exit 0

2、


[mdx@localhost mdx]$ echo '\''

>

>

>

...

(回车就显示>,永远不会出现',除非'没有在两个'之中)

Since even the escape character (\) gets a literal interpretation within single quotes, trying to enclose a single quote within single quotes will not yield the expected result.


   1 echo "Why can't I write 's between single quotes"

   2

   3 echo

   4

   5 # The roundabout method.

   6 echo 'Why can'\''t I write '"'"'s between single quotes'

   7 #    |-------|  |----------|   |-----------------------|

   8 # Three single-quoted strings, with escaped and quoted single quotes between.

   9

  10 # This example courtesy of Stéphane Chazelas.

3、太令人难以把握了,没有规律吗?

Of more concern is the inconsistent behavior of "\" within double quotes.


 bash$ echo hello\!

 hello!

 

 

 bash$ echo "hello\!"

 hello\!

 

 

 

 

 bash$ echo -e x\ty

 xty

 

 

 bash$ echo -e "x\ty"

 x       y

       

4、生词:

Quoting can also suppress echo's  "appetite" for newlines.

Weird

discrete

4.3. Bash Variables Are Untyped, 4.4. Special Variable Types

1、

http://www.linuxsir.org/main/doc/abs/HTML/untyped.html

4.3. Bash Variables Are Untyped

Example 4-4. Integer or string?

  20 c=BB34

  21 echo "c = $c"            # c = BB34

  22 d=${c/BB/23}             # Substitute "23" for "BB".

  23                          # This makes $d an integer.

  24 echo "d = $d"            # d = 2334

2、

http://www.linuxsir.org/main/doc/abs/HTML/othertypesv.html

The space allotted to the environment is limited. Creating too many environmental variables or ones that use up excessive space may cause problems.

 bash$ eval "`seq 10000 | sed -e 's/.*/export var&=ZZZZZZZZZZZZZZ/'`"

 

 bash$ du

 bash: /usr/bin/du: Argument list too long

3、

命令:basename(# Strips out path name info (see 'basename'))

[mdx@localhost abs-exercises]$ basename /home/mdx/abs-guide-3.7/ex15.sh

ex15.sh

4、比较:


16 if [ -n "$1" ]              # Tested variable is quoted.

  17 then

  18  echo "Parameter #1 is $1"  # Need quotes to escape #

  19 fi

5、得到最后一个参数:


   1 args=$#           # Number of args passed.

   2 lastarg=${!args}

   3 # Or:       lastarg=${!#}

   4 #           (Thanks, Chris Monson.)

   5 # Note that lastarg=${!$#} doesn't work.

6、待查

If a script expects a command line parameter but is invoked without one, this may cause a null variable assignment, generally an undesirable result. One way to prevent this is to append an extra character to both sides of the assignment statement using the expected positional parameter.


   1 variable1_=$1_  # Rather than variable1=$1

   2 # This will prevent an error, even if positional parameter is absent.

   3

   4 critical_argument01=$variable1_

   5

   6 # The extra character can be stripped off later, like so.

   7 variable1=${variable1_/_/}

   8 # Side effects only if $variable1_ begins with an underscore.

   9 # This uses one of the parameter substitution templates discussed later.

  10 # (Leaving out the replacement pattern results in a deletion.)

  11

  12 #  A more straightforward way of dealing with this is

  13 #+ to simply test whether expected positional parameters have been passed.

  14 if [ -z $1 ]

  15 then

  16   exit $E_MISSING_POS_PARAM

  17 fi

  18

  19

  20 #  However, as Fabian Kreutz points out,

  21 #+ the above method may have unexpected side-effects.

  22 #  A better method is parameter substitution:

  23 #         ${1:-$DefaultVal}

  24 #  See the "Parameter Substition" section

  25 #+ in the "Variables Revisited" chapter.

7、在Example 4-6. wh, whois domain name lookup中,域名查询的服务器是无效的,可以换成:"wh-inn" ) whois $1@whois.internic.net;;

8、生词:

positional

notch

4.2. Variable Assignment(echo -n,!,$())

1、echo -n的作用简单的说就是不换行,像java中的System.out.print("something");


    19 # In a 'for' loop (really, a type of disguised assignment):

    20 echo -n "Values of \"a\" in the loop are: "

    21 for a in 7 8 9 11

    22 do

    23   echo -n "$a "

    24 done

结果:Values of "a" in the loop are: 7 8 9 11

2、

下面这段的“!”不懂:

  


    10 a=`echo Hello!`   # Assigns result of 'echo' command to 'a'

    11 echo $a

    12 #  Note that including an exclamation mark (!) within a

    13 #+ command substitution construct #+ will not work from the command line,    14 #+ since this triggers the Bash "history mechanism."

    15 #  Inside a script, however, the history functions are disabled.

 

3、``相当于$()


     2 R=$(cat /etc/redhat-release)

4、英语生词:

disguised

naked

trailing

4.1. Variable Substitution(双引号,一行赋多值,未初始化变量)�

1、双引号内的变量可以保留变量值当中的超过一个空格的空格:

(abs-guide-3.7/HTML/variables.html#VARSUBN)

Example 4-1. Variable assignment and substitution


  33 hello="A B  C   D"

  34 echo $hello   # A B C D

  35 echo "$hello" # A B  C   D

  36 # As you see, echo $hello   and   echo "$hello"   give different results.

  37 #                                      ^      ^

  38 # Quoting a variable preserves whitespace.

2、可以在一行中对多个变量赋值,但是在有可能引起版本兼容性问题:

(abs-guide-3.7/HTML/variables.html#VARSUBN)

Example 4-1. Variable assignment and substitution


  57 #  It is permissible to set multiple variables on the same line,

  58 #+ if separated by white space.

  59 #  Caution, this may reduce legibility, and may not be portable.

  60

  61 var1=21  var2=22  var3=$V3

  62 echo

  63 echo "var1=$var1   var2=$var2   var3=$var3"

  64

  65 # May cause problems with older versions of "sh".

3、在没有初始化的变量上进行算术运算不是非法的,当作是"0",但是在有可能引起版本兼容性问题:

(abs-guide-3.7/HTML/variables.html#VARSUBN)


An uninitialized variable has a "null" value - no assigned value at all (not zero!). Using a variable before assigning a value to it will usually cause problems.

It is nevertheless possible to perform arithmetic operations on an uninitialized variable.

   1 echo "$uninitialized"                                # (blank line)

   2 let "uninitialized += 5"                             # Add 5 to it.

   3 echo "$uninitialized"                                # 5

   4

   5 #  Conclusion:

   6 #  An uninitialized variable has no value, however

   7 #+ it acts as if it were 0 in an arithmetic operation.

   8 #  This is undocumented (and probably non-portable) behavior.

Ctl-M(Carriage return.)(不懂)

read echo >$2 不懂

(http://www.linuxsir.org/main/doc/abs/HTML/special-chars.html)

Ctl-M

Carriage return.

   1 #!/bin/bash

   2 # Thank you, Lee Maschmeyer, for this example.

   3

   4 read -n 1 -s -p $'Control-M leaves cursor at beginning of this line. Press Enter. \x0d'

   5                                   # Of course, '0d' is the hex equivalent of Control-M.

   6 echo >&2   #  The '-s' makes anything typed silent,

   7            #+ so it is necessary to go to new line explicitly.

   8

   9 read -n 1 -s -p $'Control-J leaves cursor on next line. \x0a'

  10            #  '0a' is the hex equivalent of Control-J, linefeed.

  11 echo >&2

  12

  13 ###

  14

  15 read -n 1 -s -p $'And Control-K\x0bgoes straight down.'

  16 echo >&2   #  Control-K is vertical tab.

  17

  18 # A better example of the effect of a vertical tab is:

  19

  20 var=$'\x0aThis is the bottom line\x0bThis is the top line\x0a'

  21 echo "$var"

  22 #  This works the same way as the above example. However:

  23 echo "$var" | col

  24 #  This causes the right end of the line to be higher than the left end.

  25 #  It also explains why we started and ended with a line feed --

  26 #+ to avoid a garbled screen.

  27

  28 # As Lee Maschmeyer explains:

  29 # --------------------------

  30 #  In the [first vertical tab example] . . . the vertical tab

  31 #+ makes the printing go straight down without a carriage return.

  32 #  This is true only on devices, such as the Linux console,

  33 #+ that can't go "backward."

  34 #  The real purpose of VT is to go straight UP, not down.

  35 #  It can be used to print superscripts on a printer.

  36 #  The col utility can be used to emulate the proper behavior of VT.

  37

  38 exit 0

 

第二章习题ex2.2.sh

习题的问题:


Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting

Prev Chapter 2. Starting Off With a Sha-Bang Next

2.2. Preliminary Exercises

   1.

      System administrators often write scripts to automate common tasks. Give several instances where such scripts would be useful.

   2.

      Write a script that upon invocation shows the time and date, lists all logged-in users, and gives the system uptime. The script then saves this information to a logfile.

Prev Home Next

Starting Off With a Sha-Bang Up Basics

我的答案:

第一题:

backup database; restart web service; backup files; etc..

第二题:

#!/bin/bash

#exercise 2.2

#show date and time

echo "The date and time is: "

date

echo "lists all logged-in users: "

who

echo "the uptime is: "

uptime

echo "write the information above into file ./ex2.2.out"

#if the file ./ex2.2.out exists, delete it at first.

#to do.

echo "The date and time is: " >>  ./ex2.2.out

date >> ./ex2.2.out

echo "lists all logged-in users: " >>  ./ex2.2.out

who  >> ./ex2.2.out

echo "the uptime is: " >>  ./ex2.2.out

uptime >> ./ex2.2.out

echo "finished the work,exit."

exit 0

学习Advanced Bash-Scripting Guide(即:高级Bash脚本编程指南)

shell脚本在unix,linux世界是一种重要和基础的技术,你看看linux中大量的系统配置文件都是shell脚本就知道了。它对这类系统的灵活和高效起着非常大的作用。

用好linux就必须有shell脚本编程的能力。

为此,我特地把学习这本电子书作为一个独立的目标,这个目标是学习linux总目标的一个分目标。

学习教程:《Advanced Bash-Scripting Guide》

学习时间:有空就看,不限时间。

准备学习两遍,第一遍粗看,看英文版,对其中的全部例子过一遍;第二遍看中文版,细看重点,并纠正自己的英文理解错误,争取学英语和学shell编程一举两得。

随时把学习心得和问题记成日记,并把英文的疑问也记下来。

欢迎有兴趣、有需要的朋友加入到这个学习目标的进行中来,大家互相交流和进步。

几个有趣的shell和一个执行结果有问题的shell

这两天在看那本讲bash编程的电子书

在这本电子书中有几个有趣的shell脚本。

1、(abs-guide-3.7/HTML/sha-bang.html)

在一个文本文件的前面加上:#!/bin/more 就可以让文本文件自己显示自己; 在一个文件前面加上:#!/bin/rm 就可以自己删除自己;

2、找出存储设备的某类文件并把它们打包:

(abs-guide-3.7/HTML/special-chars.html)

  find . -mtime -1 -type f -print0 | xargs -0 tar rvf "bak.tar"

3、一个执行结果不像书上说的那样的shell:

(abs-guide-3.7/HTML/special-chars.html)


Ctl-H

"Rubout" (destructive backspace). Erases characters the cursor backs over while backspacing.

   1 #!/bin/bash

   2 # Embedding Ctl-H in a string.

   3

   4 a="^H^H"                  # Two Ctl-H's (backspaces).

   5 echo "abcdef"             # abcdef

   6 echo -n "abcdef$a "       # abcd f

   7 #  Space at end  ^              ^ Backspaces twice.

   8 echo -n "abcdef$a"        # abcdef

   9 #  No space at end                Doesn't backspace (why?).

  10                           # Results may not be quite as expected.

  11 echo; echo

(据说)目前最好的BASH教程简介及中英文版本下载(转

(转自:http://www.linuxsir.org/main/?q=node/140

Advanced Bash-Scripting Guide (包括中译本)

作者:thegrendel

主页:http://personal.riverusers.com/~thegrendel

中译本:杨春敏(chunmin.yang at gmail.com) 黄毅 (linuxprogram at gmail.com)

点评: 目前最好的BASH教程,内容全面,详尽无比,有很多脚本实例;最重要的是作者一直跟更新和修正此文档,目前的英文版本是Version 3.9;中文版最新版本是3.7.3.

目录

一、译者序

二、在线文档

三、文档下载

四、译者手记;

五、中译本更新日志;

+++++++++++++++++++++++++++++++++++++++++

正文

+++++++++++++++++++++++++++++++++++++++++

一、译者序

毫无疑问,UNIX/Linux最重要的软件之一就是shell,目前最流行的shell被称为Bash(Bourne Again Shell),几乎所有的Linux和绝大部分的UNIX都可以使用Bash。作为系统与用户之间的交互接口,shell几乎是你在UNIX工作平台上最亲密的朋友,因此,学好shell,是学习Linux/UNIX的的开始,并且它会始终伴随你的工作学习。

shell是如此地重要,但令人惊奇的是,介绍shell的书没有真正令人满意的。所幸的是,我看到了这本被人称为abs的书,这本书介绍了bash大量的细节和广阔的范围,我遇到的绝大部分的技术问题--无论是我忘记的或是以前没有发现的--都可以在这本书里找到答案。这本使用大量的例子详细地介绍了 Bash的语法,各种技巧,调试等等的技术,以循序渐进的学习方式,让你了解Bash的所有特性,在书中还有许多练习可以引导你思考,以得到更深入的知识。无论你是新手还是老手,或是使用其他语言的程序员,我能肯定你能在此书用受益。而本书除了介绍BASH的知识之外,也有许多有用的关于 Linux/UNIX的知识和其他shell的介绍。

在看到本书的英文版后,我决定把它翻译出来,在Linuxsir论坛上结识了译者之一杨春敏共同翻译这本书,600多页的书是本大部头的书,我们花了6个月的业余时间才翻译完了。

关于版权的问题,英文版的作者Mendel Cooper对英文版的版权做了详细的约定,请参考:Appendix Q. Copyright。中文版版权由译者杨春敏和黄毅共同所有,在遵守英文版版权相应条款的条件下,欢迎在保留本书译者名字和版权说明以非盈利的方式自由发布此中文版,以盈利目的的所有行为必须联系英文作者和两位中文译者以获得许可。

本书得以成稿,我(黄毅)要多谢我的女朋友,本该给予她的时间我用来了翻译,多谢你的理解,你是一个很棒的女朋友!

译者 杨春敏 黄毅

下载地址:

1、本站下载:

附件:ads-guide.zip,2163767 bytes(内含英文3.7版和中文3.7版)

2、转载地下载页面

http://www.linuxsir.org/main/?q=node/140

3、转载地的在线文档

在线浏览(中文)《高级Bash脚本编程指南》

在线浏览(英文)《Advanced Bash-Scripting Guide》