1、shell中的变量
环境变量:用于保存操作系统运行时的环境参数
位置变量:Bash将传递给脚本的参数保存在位置变量中,以便于在脚本中引用这些参数
预定义变量:有系统保留和维护的一组特殊的变量,这些变量通常用于保存程序运行状态等
自定义变量:由用户自行定义的变量。可用于用户编写脚本、多个命令键的值传递等、
2、使用数组
$0:当前进程或者脚本的名称
$*:传递给脚本的所有参数
$$:当前进程或脚本的pid号
$!:后台运行的最后一个pid号
$?:用于返回上一条命令是否成功执行。如果成功执行返回0,否则返回非
$#:保存脚本的参数个数
3、变量运算
猜数游戏脚本:
#!bin/bash
RAN = `expr $RANDOM %10`#产生10以内随机数
RAN = `expr $RAN +1`#产生的随机数加1
echo "it's a gussing game"
echo "number range: 1-10"
while true:
do
echo -n "please enter the number you guss:"
read NUM
if [$NUM -lt 1] || [10 -lt $NUM]
then
echo "you enter num out of range"
continue
fi
if [$NUM = $RAN]
then
echo "you gussed it"
unset NUM RAN #清除变量
exit 0
if [$NUM -lt $RAN]
then
echo "you enter num too small"
fi
if [$RAN -lt $NUM]
then
echo "you enter num too large"
fi
done
4、数组操作
${array[2]} //第三个元素
$array //默认第一个元素
${array[*]} //数组中所有元素
${array[@]:}//下标大于等于2的所有元素
${#array[@]}//数组中元素个数
从小到大输出数组中元素脚本实现:
#!bin/bash
array=(10,7,5,6,8,9,4,3,1,2)
LENTH=${#array[@]}
i = 0
while true:
do
j = expr `$i +1`
while ["$j" -lt $LENTH]
do
if ["$array[j]" -lt "$array[i]"]
then
temp = array[i]
array[i] = array[j]
array[j] = temp
fi
j = expr `$j` + 1
done
i = expr `$i` + 1
done
echo ${array[*]}
#清除变量
unset i j LENTH temp
unset array
5、使用函数
<pre name="code" class="cpp">#!bin/bash
function A ()
{
echo `expr $1 + $2`
}
D = `A 100 200` //调用函数A
if [$? = 0]//判断是否调用成功
then
echo "function succeed! > ./filename" #输出到指定文件
echo "D=$D"
else
echo "function failed!"
fi
6、脚本中调用函数文件
<pre name="code" class="cpp">
写好脚本后将脚本文件命名为function.example
在脚本中调用函数文件格式;<pre name="code" class="cpp">../function.example
返回函数执行状态
return : 将函数最后一条命令的执行状态作为其状态信息返回
return 0: 返回函数成功执行的信息
return 1:返回错误的信息
</pre><pre name="code" class="cpp">7、脚本实现自动查找软件依赖的文件所在的软件包
<pre name="code" class="cpp">function query()
{
LINE=0
PACKET=null
MAX =`ls $2/*.rpm |wc -l`
while true
do
LINE = `expr $LINE +1`
if [$MAX -lt $LINE]
then
echo "not find any package"
unset LINE PACKET MAX
return 1
fi
PACKET=`ls $2/*.rpm |sed -n ${LINE}p`#获取第LINE行内容
#rpm -pql 列出PACKET指向的软件包下所有文件列表
#grep -v 去掉可能的警告或错误
#/dev/null 重定向错误到系统回收池
rpm -pql $PACKET 2>/dev/null |grep -v "warning:" 2>/dev/null |grep $1 &>/dev/null
if [$? =0]
then
echo $PACKET
unset LINE PACKET MAX
return 0
fi
done
}
if [$# !=1]
then
echo "must have a parameter"
echo "usage:"$0" parameter"
exit 1
fi
PACKET_DIR = /media/server
DEPEND = $1
MESSAGE =null
echo "querying ,please wait..."
if [MESSAGE = `query $DEPEND$PACKET_DIR`]
then
echo "query is completed!"
echo "file where the package is :"
echo " " $MESSAGE
else
echo "query is completed!"
echo $MESSAGE
fi