Shell笔记

在命令执行失败后退出:

1
cmd || exit 1

子shell(把命令由括号括起来):

1
cmd | (cmd1; cmd2; cmd3) | cmd4

子shell中的cmd1可以改变工作目录,而不影响外部的cmd4

捕获键盘中断:

1
2
3
4
5
6
trap control_c SIGINT

control_c() {
echo `abort: ctrl-c`
exit
}

获得当前执行脚本的目录($0就是当前执行脚本):

1
$(dirname $0)

if测试:

1
2
3
4
5
if [ ! -d $A_DIR ]; then
mkdir -p $A_DIR
else
echo 'exists dir: '$A_DIR
fi

for循环:

1
2
3
for f in *; do 
echo $f;
done

xargs

1
ls *.old | xargs -n1 -I{} echo mv {} {}.new
  • -n N,将输入参数规整成一行N个的形式(原先的输入参数由' '\n分隔,每行个数可能不一样)
  • -I {}:由-I指定的字符串{}在每一次执行中都会被替换相应的输入参数
1
find . -type f -name "*.txt" -print0 | xargs -0 rm -f
  • find -print0指定输出的文件名以\0结尾
  • xargs -0指定\0作为参数分隔符,而不是默认的' '\n

只要把find的输出作为xargs的输入,就必须加-print0-0参数,确保以\0来分隔输出。否则,文件名中包含的空格' '会被xargs会误以为是分隔符。

1
2
cat args.txt | ( while read arg; do cat $arg; done)
# 等同于 cat args.txt | xargs -I{} cat {}

为对同一个参数执行多条命令,使用while循环,将cat $arg换成任意数量的命令