好记性不如铅笔头

linux, 操作系统

Linux Shell脚本简单实例

最近需要写一个shell脚本,就简单的笔记下用到的语法。

# /bin/sh

function simple_add()  #函数不用定义参数列表
{
	num1=$1;  # $1 表示第一个参数
	num2=$2;
	return $((num1+num2));  #返回值直接用return
}


function show_watchdog()
{
	pids=`pgrep watchdog`; #执行shell命令,可以用Tab键上面的键`,返回值直接用变量存起来。
	mypid=$$;   #查看当前进程id
	for pid in $pids
	do
	    if [[ $pid -ne $mypid ]] 
	    then
	        echo "ps -f -p "$pid;
	        ps -f -p $pid;
	    fi;
	done;
}

if [[ $1 == "add" ]]
then
	simple_add $2 $3;
	echo $2 + $3 = $?; # $? 可以获取返回值。
elif [[ $1 == "watch" ]]
then
	show_watchdog;
else
	echo "invalid input";
fi;

输出结果为:

cstriker1407@cstriker1407-x64:~$ chmod a+x simplemath.sh
cstriker1407@cstriker1407-x64:~$ ./simplemath.sh add 4 5
4 + 5 = 9
cstriker1407@cstriker1407-x64:~$ ./simplemath.sh watch
ps -f -p 22
UID        PID  PPID  C STIME TTY          TIME CMD
root        22     2  0  1月31 ?      00:00:01 [watchdog/0]
ps -f -p 23
UID        PID  PPID  C STIME TTY          TIME CMD
root        23     2  0  1月31 ?      00:00:01 [watchdog/1]
ps -f -p 28
UID        PID  PPID  C STIME TTY          TIME CMD
root        28     2  0  1月31 ?      00:00:01 [watchdog/2]
ps -f -p 33
UID        PID  PPID  C STIME TTY          TIME CMD
root        33     2  0  1月31 ?      00:00:01 [watchdog/3]
cstriker1407@cstriker1407-x64:~$ ./simplemath.sh hello
invalid input

 

发表评论

18 − 17 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据