{"title": "Shell\u811a\u672c\u7b80\u5355\u6280\u5de7\u548c\u5e38\u7528\u53c2\u8003", "update_time": "2014-12-26 10:07:20", "tags": "shell \u5e38\u7528\u53c2\u8003", "pid": "197", "icon": "linux.png"}
### 如何实现Shell脚本以DEAMON的方式运行,即实现Shell版的Fork ``` if [ "$1" != 'background' ] ; then scriptdir=$(cd "$(dirname "$0")"; pwd) scriptname=`basename $0` nohup /bin/bash ${scriptdir}/${scriptname} background &>/dev/null & exit 0 fi echo "do some thing" ``` ### 如何获取当前shell脚本所在的文件夹路径 ``` SHELLDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" ``` ### 如何正确判断变量,避免语法错误 ``` [ "x$var" == "x" ] ``` ### 如何kill一个进程树,即kill掉父进程和所有子进程(在没有找到命令之前,我在网上找到的shell版 ``` #使用方法,treekill pid treekill(){ local father=$1 childs=(`ps -ef | awk -v father=$father 'BEGIN{ ORS=" "; } $3==father{ print $2; }'`) if [ ${#childs[@]} -ne 0 ] ; then for child in ${childs[*]} do treekill $child done fi kill -9 $father } ``` ### 如何快速检测base脚本的语法错误,又不用执行脚本 ``` #以下命令 并不会真正执行脚本,只会检查xx.sh的语法 bash -n xx.sh ``` ### 如何在bash中产生一定范围的随机数 ``` ## 使用方法 ## ##get_random 10 30 function get_random() { local start_num=$1 local end_num=$2 local range1=`expr $end_num - $start_num` local range2=`expr $RANDOM % $range1` local ran_num=`expr $start_num + $range2` echo $ran_num } ```