bash脚本返回值应用

bash脚本返回值应用

应该说bash脚本对于linux系统来说具有举足轻重的意义。

这里不做展开,也不做bash脚本介绍。更多的是做一个例子,应用了bash脚本的以下特性:

  1. 输入参数
  2. 函数定义
  3. 调用可执行命令
  4. 脚本递归
  5. 条件判断

脚本具有以下功能:

  1. 支持可执行文件判断
  2. 支持单一文件可执行判断(echo $?查询)
  3. 支持多个文件可执行判断 (直接打印输出)

执行效果:

$ ./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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值