Fork me on GitHub

Linux Shell Tips

20 Jan 2014

普通删除不能删除目录,删除目录要加-rf,其中r指递归recursive,f指强制force。

$ rm -rf directory

如果不加force,删除不存在的目录时,会返回1,也就是报错,0为成功。

$ rm dontexitfile
rm: cannot remove `dontexitfile': No such file or directory
$ echo $?
1

与删除类似,当建一个已经存在的目录时,应当加入-p选项。关闭出错信息。

qinshulei@qinshulei:~/tmp$ ls
dtmp  redmine_data  result-dir  test.sh  test_up.sh  tmp
qinshulei@qinshulei:~/tmp$ mkdir result-dir
mkdir: cannot create directory `result-dir': File exists
qinshulei@qinshulei:~/tmp$ echo $?
1
qinshulei@qinshulei:~/tmp$ mkdir -p result-dir
qinshulei@qinshulei:~/tmp$ echo $?
0

shell的判断条件,其实就是使用test命令,若使用[]作为判断语句,要小心空格,内部不留空格会有问题。

qinshulei@qinshulei:~/tmp$ test -n "$dontexitvar"
qinshulei@qinshulei:~/tmp$ echo $?
1
qinshulei@qinshulei:~/tmp$ [ -n "$dontexitvar" ]
qinshulei@qinshulei:~/tmp$ echo $?
1
qinshulei@qinshulei:~/tmp$ [-n "$dontexitvar"]
[-n: command not found

其中对-n-z对字符串的比较,最好在字符串两边加引号. 在组合表达式中-a为 and,-o为 or,! 为 not.

字符串判断

  • str1 = str2      当两个串有相同内容长度时为真
  • str1 != str2      当串str1和str2不等时为真
  • -n str1        当串的长度大于0时为真(串非空)
  • -z str1        当串的长度为0时为真(空串)
  • str1         当串str1为非空时为真

数字的判断

  • int1 -eq int2    两数相等为真
  • int1 -ne int2    两数不等为真
  • int1 -gt int2    int1大于int2为真
  • int1 -ge int2    int1大于等于int2为真
  • int1 -lt int2    int1小于int2为真
  • int1 -le int2    int1小于等于int2为真

文件的判断

  • -r file     用户可读为真
  • -w file     用户可写为真
  • -x file     用户可执行为真
  • -f file     文件为正规文件为真
  • -d file     文件为目录为真
  • -c file     文件为字符特殊文件为真
  • -b file     文件为块特殊文件为真
  • -s file     文件大小非0时为真
  • -t file     当文件描述符(默认为1)指定的设备为终端时为真
  • -e file 判断文件是否存在

复杂逻辑判断

  • -a         与
  • -o        或
  • !        非

远程复制scp,从其他机器拷贝资料

qinshulei@qinshulei:~$ scp .ssh/id_rsa.pub  tangjiajia@192.168.65.88:/home/tangjiajia/test
tangjiajia@192.168.65.88's password: 
id_rsa.pub                                                                                                                                                                 100%  401     0.4KB/s   00:00   

查询机器核心数目:

$ grep "^processor" /proc/cpuinfo | wc -l
4

简单计算

$ expr 1 + 1
2

后台运行程序

$ nohup cmd 2>&1 1>xx.out &

杀死nohup的进程

$ ps -ef | grep command
$ kill -9 pid