Advanced Bash-Scripting Guide 第八至九章

2010年12月23日 星期四
/abs-guide/numerical-constants.html

echo $((0xff)) # 255 (()) 会进行十进制转换
let a="0xff"; echo $a # 255 以十进制表达结果

/abs-guide/dblparens.html
a=$((b+3)) 相当于 let "a = b + 3"
一般的数字计算用最原始的 let 赋值语句就是了,最简单的也是最安全的。

/abs-guide/opprecedence.html

((1)) || echo "hello" && echo "world" # world
|| 和 && 的优先级是一样的,这里逻辑短路止于 && 开始

((1)) || echo "hello" && ((0)) || echo "world" # world
顺序执行,跳过短路。

/abs-guide/part3.html
Part 3. Beyond the Basics

/abs-guide/variables2.html
Chapter 9. Another Look at Variables

/abs-guide/internalvariables.html
9.1. Internal Variables
1、
在一个子脚本中 $$ 返回它的父脚本的PID,而 $BASHPID 返回子脚本本身的PID

2、
不熟悉的 BASH 内部变量
1)、$CDPATH, $DIRSTACK( 借助 pushd 和 popd 命令,可以追溯访问目录), $GLOBIGNORE, $IFS(不止一个,$IFS defaults to whitespace (space, tab, and newline),,但$*使用其中的第一个), $IGNOREEOF, $LINENO, $REPLY, $BASH_SUBSHELL,

3、
shopt -s dotglob

4、
kill -s 14 $$ #发送信号14(ALRM)给当前所在的脚本

trap Int14Vector $TIMER_INTERRUPT
trap [-lp] [[arg] sigspec ...]
The command arg is to be read and executed when the shell receives signal(s) sigspec.

5、
疑问:
timeout.sh
stty -icanon min 0 time ${timeout}0

6、
Bash 中限时输入最简单的方法是使用 read -t

7、
$ENV, $LOGNAME, $MAIL, $TERM, $USER, $USERNAME, $SHELL 不是 Bash 内建变量。

8、
for arg in "$*" #全部参数当作一个字符串
for arg in "$@" #各个参数分开
for arg in $* #各个参数分开

9、
在移位(shift)命令中,$@ 保留剩下的命令行参数

10、
Example 9-7. Inconsistent $* and $@ behavior
1)、
set --
-- If no arguments follow this option, then the positional
parameters are unset. Otherwise, the positional parame‐
ters are set to the args, even if some of them begin
with a -.
$@ 和 $* 参数仅在双引号中有区别

2)、
todo:
例子太繁杂,以后有需要时再学习。

3)、(重要)
$!
杀掉挂起的后台脚本:

# This example by Matthew Sage.
# Used with permission.

TIMEOUT=30   # Timeout value in seconds
count=0

possibly_hanging_job & {
        while ((count < TIMEOUT )); do
                eval '[ ! -d "/proc/$!" ] && ((count = TIMEOUT))'
                # /proc is where information about running processes is found.
                # "-d" tests whether it exists (whether directory exists).
                # So, we're waiting for the job in question to show up.
                ((count++))
                sleep 1
        done
        eval '[ -d "/proc/$!" ] && kill -15 $!'
        # If the hanging job is running, kill it.
}

疑问:
经初步试验,不要 eval 测试下面代码仍然通过,为什么上面要加上呢?

#!/bin/bash

sleep 100 &
echo "the job is $!"
i=0
while [ 1 ]
do
let "i++"
[ -d "/proc/$!" ] && echo "$i: $!" && kill -15 $! && kill -15 $$
sleep 1
done

4)、(重要)
上面代码中 eval 的用法:(参考: http://www.softpanorama.org/Utilities/eval.shtml )
摘录示例:
# CMD='date | wc'
# $CMD
usage: date [-a sss.fff] [-u] [tformat] [mmddhhmm[yy]] #把 | wc 当成 date 的参数了,报告用法错误。
# eval $CMD