shell讲解-小案例
一、文件拷贝输出检查
下面测试文件拷贝是否正常,如果cp命令并没有拷贝文件myfile到myfile.bak,则打印错误信息。注意错误信息中basename $0
打印脚本名。如果脚本错误退出,一个好习惯是显示脚本名并将之定向到标准错误中。用户应该知道产生错误的脚本名。
[root@localhost ~]# cat ifcp.sh #!/bin/sh # ifcp.sh if cp myfile myfile.bak; then echo "good copy" else echo "`basename $0`: error could not copy the file" >&2 fi [root@localhost ~]# ./ifcp.sh cp: cannot stat `myfile': No such file or directory ifcp.sh: error could not copy the file
[root@localhost ~]# cat ifcp.sh #!/bin/sh # ifcp.sh if cp myfile myfile.bak > /dev/null 2>&1; then echo "good copy" else echo "`basename $0`: error could not copy the file" >&2 fi [root@localhost ~]# ./ifcp.sh ifcp.sh: error could not copy the file
上面当中>/dev/null表示任何标准输出都定向到那个无尽的“黑洞”/de/null中,然后2>&1表示错误输出也是到/dev/null中,&1表示前面的那个/dev/null,脚本运行时,所有输出包括错误重定向至系统垃圾堆。
二、五颜六色的脚本
#!/bin/bash clear echo -e "