bash脚本返回值应用
bash脚本返回值应用
应该说bash脚本对于linux系统来说具有举足轻重的意义。
这里不做展开,也不做bash脚本介绍。更多的是做一个例子,应用了bash脚本的以下特性:
- 输入参数
- 函数定义
- 调用可执行命令
- 脚本递归
- 条件判断
脚本具有以下功能:
- 支持可执行文件判断
- 支持单一文件可执行判断(echo $?查询)
- 支持多个文件可执行判断 (直接打印输出)
执行效果:
$ ./bash_script.sh bash_script.sh a.out test.c ttt.txt test.txt
x:./bash_script.sh bash_script.sh
x:./bash_script.sh a.out
x:./bash_script.sh test.c
n:./bash_script.sh ttt.txt
n:./bash_script.sh test.txt
脚本代码:
#!/bin/sh
# HELP
# param: file name
# description: check file existed and exectuable, return 1 or 0 (for NOT existed or unexectuable file)
# x: file existed and exectuable
# n: normal file
# e.g.
# $ ./bash_script.sh test.txt a.out
# n:./bash_script.sh test.txt
# x:./bash_script.sh a.out
# PRINT () {if [ $1 = 1 ]; thenecho "x:$2 $3"elseecho "n:$2 $3"fi
}HELP () {echo $0echo "param: file name"echo "description: check file existed and exectuable, return 1 or 0 (for NOT existed or unexectuable file)"echo "x: file existed and exectuable"echo "n: normal file"echo "e.g. "echo "$ ./bash_script.sh test.txt a.out"echo "n:./bash_script.sh test.txt"echo "x:./bash_script.sh a.out"
}EXEC_FILE_NAME=$0case $# in0) HELP#EXEC_COMMAND="$EXEC_FILE_NAME $EXEC_FILE_NAME";#bash $EXEC_COMMAND#ERR=$?#PRINT $ERR $EXEC_FILE_NAME $EXEC_FILE_NAMEbreak;;1) if [ -x "$1" ]; thenexit 1elseexit 0fibreak;;*) EXEC_COMMAND="$EXEC_FILE_NAME $1";bash $EXEC_COMMANDERR=$?PRINT $ERR $EXEC_FILE_NAME $1shiftEXEC_COMMAND="$0 $@"bash $EXEC_COMMANDERR=$?if [ $# = 1 ]; thenPRINT $ERR $0 $@fi
esac
特殊场景(耗时易失败任务)应用:
注1:循环判断(具体任务和判断条件根据实际情况调整)。
注2:问题来源:国外网站apt-get一些开源,比如:flightgear经常失败,且耗时异常长(基本上需要24小时以上)。
actions() {check_if_file_present# Do other stuff
}actions #1st execution
while [ current_time <= $cutoff ]; doactions # Loop execution
done
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
