bash 小技巧

1. 用&& ||简化if else
gzip -t a.tar.gz
if [[ 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;;
        ?) ;;
    esac
done
shift $((OPTIND-1))

3. 获取文件大小
$ stat -c %s fw8ben.pdf

4. 字符串替换
替换第一个:${string//pattern/replacement}
替换全部:${string//pattern/replacement}
$ a='a,b,c'
$ 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_folder
rsync -r -t -v /source_folder [user@]host:/destination_folder 
注:命令执行后destination_folder内将包含一个名为source_folder的目录。

8. 批量rename
为所有的txt文件加上.bak后缀:
rename '.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; done
for line in $(cat a.txt); do echo $line; done
for f in *.txt; do echo $f; done
while read line ; do echo $line; done < a.txt
cat a.txt | while read line; do echo $line; done

11. 进程终止
pkill swiftfox #根据名称终止进程
kill -9 <pid> #根据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. 定时关机
nohup shutdown -t 10 +30 &           
#-t 10: warning与kill signal的间隔时间10s;+30: 分钟后定时关机

16. 模式提取
$echo '2011-07-15 server_log_123.log hello world' | grep -o 'server_log_[0-9]\+\.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 '\r'
$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 ‘[A-Z]’ ‘[a-z']’ < foo.txt

23.读取多个域到变量

$ read a b c <<< “xxx yyy zzz”

$ echo $b

yyy

24.遍历数组

array=( one two three )
for i in ${array[@]}
do
     echo $i
done

猜你喜欢

转载自marshzg.iteye.com/blog/1207135