#!/bin/bash
# max.sh: 取两个Maximum of two integers.
E_PARAM_ERR=250 # 如果传给函数的参数少于两个时,就返回这个值。
EQUAL=251 # 如果两个参数相等时,就返回这个值。
# 任意超出范围的
#+ 参数值都可能传递到函数中。
max2 () # 返回两个数中的最大值。
{ # 注意:参与比较的数必须小于250.
if [ -z "$2" ]
then
return $E_PARAM_ERR
fi
if [ "$1" -eq "$2" ]
then
return $EQUAL
else
if [ "$1" -gt "$2" ]
then
return $1
else
return $2
fi
fi
}
max2 33 34
return_val=$?
if [ "$return_val" -eq $E_PARAM_ERR ]
then
echo "Need to pass two parameters to the function."
elif [ "$return_val" -eq $EQUAL ]
then
echo "The two numbers are equal."
else
echo "The larger of the two numbers is $return_val."
fi
exit 0
# 练习 (easy):
# ---------------
# 把这个脚本转化为交互脚本,
#+ 也就是,修改这个脚本,让其要求调用者输入2个数。
count_lines_in_etc_passwd()
{
[[ -r /etc/passwd ]] && REPLY=$(echo $(wc -l < /etc/passwd))
# 如果 /etc/passwd 可读,让 REPLY 等于 文件的行数.
# 这样就可以同时返回参数值与状态信息。
# 'echo' 看上去没什么用,可是...
#+ 它的作用是删除输出中的多余空白符。
}
if count_lines_in_etc_passwd
then
echo "There are $REPLY lines in /etc/passwd."
else
echo "Cannot count lines in /etc/passwd."
fi
# 感谢, S.C.
#!/bin/bash
# 将阿拉伯数字转化为罗马数字。
# 范围:0 - 200
# 比较粗糙,但可以正常工作。
# 扩展范围, 并且完善这个脚本, 作为练习.
# 用法: roman number-to-convert
LIMIT=200
E_ARG_ERR=65
E_OUT_OF_RANGE=66
if [ -z "$1" ]
then
echo "Usage: `basename $0` number-to-convert"
exit $E_ARG_ERR
fi
num=$1
if [ "$num" -gt $LIMIT ]
then
echo "Out of range!"
exit $E_OUT_OF_RANGE
fi
to_roman () # 在第一次调用函数前必须先定义它。
{
number=$1
factor=$2
rchar=$3
let "remainder = number - factor"
while [ "$remainder" -ge 0 ]
do
echo -n $rchar
let "number -= factor"
let "remainder = number - factor"
done
return $number
# 练习:
# ---------
# 1) 解释这个函数如何工作
# 提示: 依靠不断的除,来分割数字。
# 2) 扩展函数的范围:
# 提示: 使用echo和substitution命令.
}
to_roman $num 100 C
num=$?
to_roman $num 90 LXXXX
num=$?
to_roman $num 50 L
num=$?
to_roman $num 40 XL
num=$?
to_roman $num 10 X
num=$?
to_roman $num 9 IX
num=$?
to_roman $num 5 V
num=$?
to_roman $num 4 IV
num=$?
to_roman $num 1 I
# 成功调用了转换函数。
# 这真的是必须的么? 这个可以简化么?
echo
exit