几个简单的shell小程序

90 阅读1分钟

@说明

  • GitHub地址:github.com/ouyangsuo/S…
  • 以下shell脚本,完成后全部拷贝至系统的公共可执行程序目录,使得可以在任意目录下执行
sudo cp hello calc mcp fileinfo guessnum /bin/

@HelloShell(/bin/hello)

#!/bin/bash
#↑声明shell解释器位置

word="Hello Shell"
echo "Hello Shell!"

这里写图片描述

@数学计算(/bin/calc)

#!/bin/bash
# calc --add 3 4 执行结果为7

#第一个参数为--add时,做加法
if [[ $1 = "--add" ]];then
echo --add
echo $(($2+$3))

#第一个参数为--sub时,做减法
elif [[ $1 = "--sub" ]];then
echo --sub
echo $(($2-$3))

#第一个参数为--mul时,做乘法
elif [[ $1 = "--mul" ]];then
echo --mul
echo $(($2*$3))

#第一个参数为--div时,做除法
elif [[ $1 = "--div" ]];then
echo --div
echo $(($2/$3))

#第一个参数为--div时,做求余
elif [[ $1 = "--mod" ]];then
echo --mod
echo $(($2%$3))

#第一个参数为其它时,提示错误
else
echo $1
echo fuck off,不支持的操作符
fi

这里写图片描述

@显示文件信息(/bin/fileinfo)

#!/bin/bash
#fileinfo ~/hello 显示该文件的权限和内容

fileinfo(){


	# 如果文件不存在,报错退出
	if [[ ! -e $1 ]];then
		echo "$1 doesn't exist!"
		return 0
	fi

	echo $1:

	#判断和输出文件的读写执行权限
	if [[ -r $1 ]];then
		echo -n "readable,"
	else
		echo -n "NOT-readble,"
	fi

	if [[ -w $1 ]];then
		echo -n "writable,"
	else
		echo -n "NOT-writable,"
	fi

	if [[ -x $1 ]];then
		echo "executable"
	else
		echo "NOT-executable"
	fi

	#通过Linux的标准命令,输出文件内容
	echo -e "\ncontents":
	echo ====================
	cat $1
	echo ====================

}

# 调用函数,传入文件位置参数
fileinfo $1

这里写图片描述

@自定义的文件拷贝(/bin/mcp)

#!/bin/bash
#用户通过mcp srcfile dstfile实现拷贝
#通过mcp -a srcfile dstfile实现追加
#拷贝完成后询问用户是否立即查看

docp(){

#判断是新建还是追加
append=0
if [[ $1 = "-a" ]];then
	append=1
	srcfile=$2
	dstfile=$3
else
	append=0
	srcfile=$1
	dstfile=$2
fi
echo "srcfile:$srcfile,dstfile:$dstfile"

#判断源文件是否存在
if [[ ! -e $srcfile ]];then
	echo "stupid! souce file does not exist!"
	return 0
fi

#如果目标文件不存在则创建
if [[ ! -e $dstfile ]];then
	touch $dstfile
fi

#写入文件
if [[ $append -eq 1 ]];then
	cat < $srcfile >> $dstfile
else
	cat < $srcfile > $dstfile
fi

#询问用户是否要查看目标文件
echo -n "$srcfile written to $dstfile successfully! read it now?[y/n]:"
read temp
if [[ $temp = 'y' ]];then
	echo "content:"
	echo ====================
	cat < $dstfile
	echo ====================
fi

}

#调用函数,传入参数
docp $1 $2 $3


这里写图片描述

@猜数字小游戏(/bin/guessnum)

#!/bin/bash

#生成随机数,此处的rand命令需要安装一下
answer=`rand --max 1000`
#answer=$(cat /dev/urandom | head -n 10 | cksum | awk -F ' ' '{print $1}')
#answer=$(($answer%1000))
echo $answer

while true
do
	#提示用户输入
	echo -n "please enter a num between 0~1000:"
	read guess

	#看答案
	if [[ $guess = "drop it" ]];then
		echo "the answer is:$answer"
		break
	fi

	#对比
	if [[ $guess -eq $answer ]];then
		echo "bingo!the answer is:$answer"
		break
	elif [[ $guess -gt $answer ]];then
		echo "too big!"
	else	
		echo "too small!"		
	fi
done

echo "GAME OVER!"

这里写图片描述