您的位置:首页 > 运维架构 > Shell

shell实例(十二) ----内部命令和内建命令(printf,read)

2011-03-10 16:41 375 查看
说明:read -s -n1 -p:

-s:意味着不打印输出

-n: N:只接受N个字符

-p:读取输入之前打印出后边的提示符

1.一个fork出多个自身实例的脚本

#! /bin/sh
PIDS=$(pidof sh $0) -----$()相当于两个反引号(``),pidof sh $0:查找出sh 和 $0(脚本本身)相关的pid
P_arry=( $PIDS )
echo $PIDS
let "instances = ${#P_array[*]} - 1"
echo "$instances instances(s) of this script running."
echo "[Hit Ctrl-C to exit.]"
echo

sleep 1
sh $0
exit 0s

2.使用printf

#! /bin/sh
PI=314159265358979
DecimalConstant=31373
Message1="Greetings,"
Message2="Earthling."

echo

printf "Pi to 2 decimal places = %1.2f" $PI ----------%1.2f浮点数保留2位小数
echo
printf "Pi to 9 decimal places = %1.9f" $PI

printf "/n"

printf "Constant = /t%d/n" $DecimalConstant -----------%d输出整数
#echo $Message1
#echo $Message2
printf "%s %s /n" $Message1 $Message2 ------------%s输出字符串
echo
echo

Pii2=$(printf "%1.12f" $PI)
echo "Pi to 12 decimal places = $Pii2"

Msg=`printf "%s %s /n" $Message1 $Message2`
echo $Msg; echo $Msg
exit 0

3.使用read来进行变量分配

#! /bin/sh
echo -n "Enter the values of variables 'var1' and 'var2' : "
read var1 var2
echo "var1 = $var1 var2 = $var2"

read
echo "var3 = "$REPLY""

exit 0

4.检测方向键

#! /bin/sh
arrowup='/[A'
arrowdown='/[B'
arrowrt='/[C'
arrowleft='/[D'
insert='/[2'
delete='/[3'

SUCCESS=0
OTHER=65

echo -n "Press a key ... "
read -n3 key
echo Key: "$key"
echo -n "$key" | grep "$arrowup"
if [ "$?" -eq $SUCCESS ]
then
echo "Up-arrow key pressed."
exit $SUCCESS
fi

echo -n "$key" | grep "$arrowdown"
if [ "$?" -eq $SUCCESS ]
then
echo "Down-arrow key pressed."
exit $SUCCESS
fi

echo -n "$key" | grep "$arrowrt"
if [ "$?" -eq $SUCCESS ]
then
echo "Right-arrow key pressed."
exit $SUCCESS
fi

echo -n "$key" | grep "$arrowleft"
if [ "$?" -eq $SUCCESS ]
then
echo "Left-arrow key pressed."
exit $SUCCESS
fi

echo -n "$key" | grep "$insert"
if [ "$?" -eq $SUCCESS ]
then
echo "/"Insert/" key pressed."
exit $SUCCESS
fi

echo -n "$key" | grep "$delete"
if [ "$?" -eq $SUCCESS ]
then
echo "/"Delete/" key pressed."
exit $SUCCESS
fi

echo " Some other key pressed."
exit $OTHER

5.通过文件重定向来使用read命令

#! /bin/sh
read var1 < 11-6.sh
echo "var1 = $var1"
read var2 var3 < 11-6.sh
echo "var2= $var2 var3=$var3"
echo "----------------------------------"

while read line
do
echo "$line"
done < 11-6.sh

echo "--------------------------------"

echo "List of all users:"
OIFS=$IFS; IFS=:
while read name passwd uid gid fullname ignore
do
echo "$name ($fullname)"
done < /etc/passwd
IFS=$OIFS
echo "--------------------------------"

echo "List of all users:"
while IFS=: read name paswd uid gid fullname ignore
do
echo "$name ($fullname)"
done < /etc/passwd

echo
echo "/$IFS still $IFS"

exit 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: