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 ]; then
echo "x:$2 $3"
else
echo "n:$2 $3"
fi
}
HELP () {
echo $0
echo "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=$0
case $# in
0) HELP
#EXEC_COMMAND="$EXEC_FILE_NAME $EXEC_FILE_NAME";
#bash $EXEC_COMMAND
#ERR=$?
#PRINT $ERR $EXEC_FILE_NAME $EXEC_FILE_NAME
break;;
1) if [ -x "$1" ]; then
exit 1
else
exit 0
fi
break;;
*) EXEC_COMMAND="$EXEC_FILE_NAME $1";
bash $EXEC_COMMAND
ERR=$?
PRINT $ERR $EXEC_FILE_NAME $1
shift
EXEC_COMMAND="$0 $@"
bash $EXEC_COMMAND
ERR=$?
if [ $# = 1 ]; then
PRINT $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 ]; do
actions # Loop execution
done