- 海之寻趣
- Ranler
- 2014-10-23 11:55
- CC BY-NC-SA
Bash Shell(2)
Tips
sh
means/bin/sh
command, equal with/bin/bash
in almost Linux-
.
equal withsource
command -
"
阻止解释大部分特殊字符,$,`,\除外 '
阻止解释全部特殊字符:
Shell空命令, no op, 等价Shell内的true。也可用来执行非活动任务的shell命令,如: ${VAR:="some default"}
()
- 命令组,启动子Shell执行。子Shell中的变量时局部的。
- 数组,如
array=(1 2 3)
{}
- 括号扩展,扩展
{}
两边空格之间的部分,如a{b,c,d}e
=>abe ace ade
- 代码块, 等价于创建匿名函数,但是其中变量作用域是全局。可将代码块的结果进行I/O重定向。
- echo 打开"-e"选项,在输出的字符串中打开转义,格式化输出
- egrep 扩展正则表达式,等价
grep -E
Function Library
Define functions in non-runable file(functions.sh):
#!/bin/echo Warning: this library should not be sourced!
ostype ()
{
osname=`uname -s`
OSTYPE=UNKNOWN
case $osname in
"FreeBSD") OSTYPE=FREEBSD
;;
"SunOS") OSTYPE="SOLARIS"
;;
"Linux") OSTYPE="LINUX"
;;
esac
return 0
}
and in user script:
source functions.sh # or . functions.sh
...
Arrays
declare -a ARY1=(`ls -l`)
declare -a ARY2=(aa bb cc)
echo ${ARY1[0]}
echo ${ARY2[1]}
echo ${ARY1[@]} # all items in array
ehco ${#ARY1[*]} # array length
条件判断
[]
和test
等价,[
是shell内建命令或/usr/bin/[
,]
表示比较完成。- 条件测试
- 数组元素
[[]]
- 测试,比
[]
更加通用
比较:
| 字符串 | = | != | > | >= | < | <= | -z | -n | | 数字 | -eq | -ne | -gt | -ge | -lt | -le |
&&
等价-a
||
等价-o
例子:
ZERO=0
if [ $ZERO -eq 0 ];then echo $ZERO;fi
if test $ZERO -eq 0;then echo $ZERO;fi
test $ZERO -eq 0 && echo $ZERO # if return true
test $ZERO -eq 0 || echo $ZERO # if return false
[ $ZERO -eq 0] && {
echo $ZERO # if return true
}
getopts
OPTINT=1
while getopts lf:h ARGS; do
case $ARGS in
l)
...
;;
f)
FILE=$OPTARG # 如果选项后跟着冒号,表示选项后跟的是参数
...
;;
h)
...
;;
*)
usage
;;
esac
done
noclobber
The setting shell parameter set -o noclobber
(bash, ksh) will prevent > from clobbering by making it issue an error message instead:
echo "Hello, world" >file.txt
echo "This will overwrite the first greeting." >file.txt
set -o noclobber
echo "Can we overwrite it again?" >file.txt
-bash: file.txt: cannot overwrite existing file
echo "But we can use the >| operator to ignore the noclobber." >|file.txt
# Successfully overwrote the contents of file.txt using the >| operator
set +o noclobber # Changes setting back
文件句柄
-
重定向stdio
或stdout
# 3~9
exec 3< file1 # 读模式
exec 4> file2 # 覆盖写模式
exec 5>> file3 # 追加写模式
exec 6<> file4 # 读写模式
read line <&3
echo "123" >&4
exec 3>&- # 关闭文件描述符
set a BASH variable equal to the output from a command:
OUTPUT="$(ls -1)"
echo "${OUTPUT}" # Quoting (") does matter to preserve multi-line values.
数学计算
- expr
ans=`expr $a + $b`
ans=`expr $a - $b`
ans=`expr $a \* $b`
ans=`expr $a / $b`
ans=`expr $a % $b`
- shell内置(bash,ksh)
ans=$(($a+$b))
ans=$(($a-$b))
ans=$(($a*$b))
ans=$(($a/$b))
ans=$(($a%$b))
ans=$(($a**$b) # 指数运算
- bc
ans=`echo "$a+$b"|bc`
ans=`echo "$a-$b"|bc`
ans=`echo "$a*$b"|bc`
ans=`echo "$a/$b"|bc`
ans=`echo "$a%$b"|bc`
ans=`echo "$a^$b"|bc` # 指数运算
ans=`echo "scale=5;$a/$b"|bc` # 精度为5的运算,结果为小数
ans=`echo "scale=5;s($a)"|bc -l` # 调用sin函数
advanced commands
- cut 列字符串、字节、域的选择
- sed 查找替换
- awk (条件)列选择
- expect 自动输入交互数据