Shell 小技巧
1. 用&& ||简化if elsegzip -t a.tar.gzif [[ 0 == $? ]]; then echo "good zip"else echo "bad zip"fi
可以简化为:
gzip -t a.tar.gz && echo "good zip" || echo "bad zip"
2. 命令行参数解析
while getopts ":a:b:c" OPT; do case $OPT in a) arg_a=$OPTARG";; b) arg_b=$OPTARG;; c) arg_c=true;; ?) ;; esacdoneshift $((OPTIND-1))
3. 获取文件大小
$ stat -c %s fw8ben.pdf
4. 字符串替换
替换第一个:${string/pattern/replacement}替换全部:${string//pattern/replacement}
$ a='a,b,c'
$ echo ${a/,/ } #替换第一个
$ echo ${a//,/ }#替换全部
$ a b c
5. Contains子字符串?
string='My string'if [[ $string == *My* ]]; then echo "It's there!"fi
6. 重定向
1>File 2>&1
7. 备份
rsync -r -t -v /source_folder /destination_folderrsync -r -t -v /source_folder host:/destination_folder
注:命令执行后destinationfolder内将包含一个名为sourcefolder的目录。
8. 批量rename
#为所有的txt文件加上.bak后缀:rename '.txt' '.txt.bak' *.txt#去掉所有的bak后缀:rename '.bak' '' *.bak
9. 字符集设置
echo $LANG/etc/sysconfig/i18n
10. for/while循环
for ((i=0; i < 10; i++)); do echo $i; donefor line in $(cat a.txt); do echo $line; donefor f in *.txt; do echo $f; donewhile read line ; do echo $line; done < a.txtcat a.txt | while read line; do echo $line; done
11. 进程终止
pkill swiftfox #根据名称终止进程kill -9#根据pid终止进程
12. find
find ~/tmp -name "*abc*.txt" -mtime -5 #在~/tmp目录下查找名为*abc*.txt且修改时间为5天内的文件
13. 删除空行
cat a.txt | sed -e '/^$/d'$ (echo "abc "; echo ""; echo "ddd";) | awk '{ if(0!=NF) print $0;}'
14. 比较文件修改时间
` file1`.`txt -nt file2`.`txt ` && echo true || echo false #-nt means "newer than"
15. 定时关机
# -t 10: warning与kill signal的间隔时间10s;+30: 分钟后定时关机 nohup shutdown -t 10 +30 &
16. 模式提取
$echo '2011-07-15 server_log_123.log hello world' | grep -o 'server_log_\+\.log' server_log_123.log$echo '2011-07-15 server_log_123.log hello world' | sed 's/.*\(server_log_.*\.log\).*/\1/' server_log_123.log
17. DOS转Unix
$cat a.txt | tr -d '
' $dos2unix a.txt
18.实现Dictionary结构
hput() { eval "hkey_$1"="$2"} hget() { eval echo '${'"hkey_$1"'}'} $ hput k1 aaa $ hget k1 aaa
19.去掉第二列
$ echo 'a b c d e f' | cut -d ' ' -f1,3- a c d e f
20.把stderr输出保存到变量
$ a=$( (echo 'out'; echo 'error' 1>&2) 2>&1 1>/dev/null)$ echo $a error
21.删除前3行
$cat a.txt | sed 1,3d
22.大小写转换
$ echo $foo | tr '[:lower:]' '[:upper:]' $ tr ‘’ ‘’ < foo.txt
23.读取多个域到变量
$ read a b ca.bin $ xxd a.bin 0000000: feff 0000
页:
[1]