echo -n 不换行输出
#!/bin/bash
#
declare -i MAX=0
declare -i MIN=0
for I in {1..10};do
MYRAND=$RAMDOM
[ $I -eq 1 ] && MIN=$MYRAND
if [ $I -le 9 ];then
echo -n "$MYRAND,"
else
echo "$MYRAND"
fi
[ $MYRAND -gt $MAX ] && MAX=$MYRAND
[ $MYRAND -lt $MIN ] && MIN=$MYRAND
done
echo $MAX
echo $MAX
面向过程:
控制结构
顺序结构
选择结构
循环结构
选择结构:
if:单分支 双分支 多分支
if CONDITION;then
statement
...
fi
if CONDITION;then
statement
...
else
statement
...
fi
if CONDITION;then
statement
elif CONDITION;then
statement
else CONDITION;then
statement
fi
case 语句;选择结构
变量的值
case SWITCH in
value1)
statement
...
;;
value2)
statement
...
;;
*)
statement
...
;;
esac
#!/bin/bash
#
case $1 in
[0-9])
echo "A digit" ;;
[a-z])
echo "Lower" ;;
[A-z])
echo "Upper" ;;
*)
echo "Spacial character." ;;
esac
接受参数,start stop restart status其中之一
#!/bin/bash
#
case $1 in
‘start‘)
echo "start server ..." ;;
‘stop‘)
echo "stop server ..." ;;
‘restart‘)
echo "Restart server ..." ;;
‘status‘)
echo "running ..." ;;
*)
echo "basename $0 {start|restart|status|stop}" ;;
esac
写一个脚本,可以接收选项及参数,而后获取每一个选项,及选项的参数;
并能根据选项及参数做出特点的操作,比如
adminusers.sh --add tom,jerry
--del tom,blair
-v|--verbose
-h|--help
vi debug.sh
#!/bin/bash
#
DEBUG=0
case $1 in
-v|--verbose)
DEBUG=1 ;;
*)
echo "Unkown options"
exit 7
;;
esac
[ $DEBUG -eq 1 ] && echo hello
vi adduser.sh
#!/bin/bash
#
DEBUG=0
ADD=0
DEL=0
case $1 in
-v|--verbose)
DEBUG=1 ;;
esac
useradd tom &> /dev/null
[ $DEBUG -eq 1 ] && echo "Add user finished"
vim adminusers.sh
#!/bin/bash
#
DEBUG=0
ADD=0
DEL=0
for I in `seq 1 $#`;do
case $1 in
-v|--verbose)
DEBUG=1
shift $1 ;;
-h|--help)
echo "Usage:`bashname $0` --add USER_LIST --del USER_LIST -v| verbose -h|--help "
exit 0 ;;
--add)
ADD=1
ADDUSERS=$2
shift 2 ;;
--del)
DEL=1
DELUSERS=$2
shift 2 ;;
#*)
# echo "Usage:`bashname $0` --add USER_LIST --del USER_LIST -v| # verbose -h|--help "
# exit 7 ;;
esac
done
if [ $ADD -eq 1 ];then
for USERS in `echo $ADDUSERS | sed ‘[email protected],@ @g‘` ;do
if id $USER &> /dev/null;then
[ $DEBUG -eq 1 ] && echo "$USER exist."
else
useradd $USER
[ $USER -eq 1 ] && echo "$USER finished"
fi
done
fi
if [ $DEL -eq 1 ];then
for USERS in `echo $DELUSERS | sed ‘[email protected],@ @g‘` ;do
if id $USER &> /dev/null;then
usedell -r $USER;
[ $DEBUG -eq 1 ] && echo "Delete $USER finished."
else
[ $USER -eq 1 ] && echo "$USER not exist"
fi
done
fi