in Blog Posts, Solution

Linux Tips (1)

这里记录一些小技巧,比较杂。

1. bash下,x{a,b}会被展开为xa xb,很适合文件备份。
如果你要复制一份a.txt作为备份,到a.txt的路径又太长了,这么写比较方便。

cp /a/long/long/long/path/to/file/a.txt{,bak}

2. vim下,要把某些内容替换成为行号,可以用\=line(“.”)来处理。“.”用来连接行号和其它内容。

:%s/xxxx/\=line(".") . " "/g

3. bash脚本下,如果要写多行到文件里,可以用

cat > file << EOF
file content line 1
file content line 2
file content line 3
file content line 4
EOF

这是一种固定写法,从第二行起,遇到EOF就停止,把之前的内容写到file里。EOF也可以换成别的。

4. Trap SIGINT的时候记得要处理SIGINT信号。

#! /bin/bash

trap "echo 'hello'; exit 1" SIGINT SIGTERM

while [ 1=1 ];
do
    sleep 1
done

exit 1这部分是必须的,否则虽然按下Ctrl + C的时候会显示hello,但是脚本不会被终止。

Write a Comment

Comment