学习循环,见了很多的for,while,或者until,而select用的比较少,这里是稍微总结下select这个循环。
基本结构:
select VALUE in LIST
do
COMMAND
done
而现实出来的结构大概为值前有个数字,选择的那个数字,是$REPLY的值,这里不懂没事,可以继续看下面的程序。$PS3变量相当于shell的默认提示符,默认为空,可以配合select使用。
#!/bin/bash #save $PS3 oPS3=$PS3 PS3="请选择喜欢的水果q退出:" select fruit in pear apple banana others quit do if [ ! -z "$fruit" ] ; then [ "$fruit" == "quit" ] && exit 0 || echo "you choosed $REPLY and you like $fruit" else echo "wrong argv $REPLY" fi done #restore $PS3 PS3=$oPS3
执行结果
[[email protected] shell]# ./select.sh 1) pear 2) apple 3) banana 4) others 5) quit 请选择喜欢的水果q退出:1 you choosed 1 and you like pear 请选择喜欢的水果q退出:6 wrong argv 6 请选择喜欢的水果q退出:5
再写个程序,顺便说一下常用的字符串到数字运算,自己写的,有点蹩脚,这个程序要注意有的地方不能有空格比如let,而expr则必须有空格,为了保险,我使用了单引号
#!/bin/bash #save PS3 oPS3=$PS3 PS3="choose the way:" function way1 (){ echo "you are using () to add" tmp1=$((nu1 + nu2)) echo "value is $tmp1" } function way2(){ echo "you are using expr to add" echo "value is `expr ${nu1} + ${nu2}`" } function way3(){ echo "you are using let to add" let tmp2=${nu1}+${nu2} echo "value is $tmp2" } read -p "please input two to test:" nu1 nu2 select cal in ‘(())‘ ‘expr‘ ‘let‘ ‘q‘ do case $cal in ‘(())‘) way1;; ‘expr‘) way2;; ‘let‘) way3;; ‘q‘) exit 0;; * ) echo "wrong argv";; esac done #restore PS3 PS3=$oPS3
执行结果为
[[email protected] shell]# ./select2.sh please input two to test:2 3 1) (()) 2) expr 3) let 4) q choose the way:3 you are using let to add value is 5 choose the way:1 you are using () to add value is 5 choose the way:2 you are using expr to add value is 5 choose the way:4
和本次无关
突然想写这样一个脚本
对每一个非系统用户说声hello,用户名,i know you are form 用户组名
我的思路就是shell不能是/sbin/nologin,家目录不能为/sbin我的文件时这样子的
好吧,我承认这个更蹩脚,改天看下详细的awk命令
#!/bin/bash #change ps2 tmp=`cat /etc/passwd` cat /etc/passwd 2>/dev/null|grep -v /sbin/nologin|grep -v /sbin|awk -F ":" ‘{print "hello,"$1",i know you are from "$5"."}‘
执行结果为:
[[email protected] shell]# ./while.sh hello,root,i know you are from root. hello,liuliancao,i know you are from liuliancao.
改天学了awk再修改下吧
这里有个书上写的关于变量书写的tips:
简写如下
a)常数,字符串,文件名建议大写
b)数字等数据变量建议小写
c)命名本质没有好坏之分,重要的是始终保持一种风格,好像这点我得继续努力...
时间: 2024-10-22 12:52:34