案例4-1:已知/etc/passwd文件中的各项以:分隔,若使用awk命令处理/etc/passwd文件,提取其中的第1项和第3项,并使用空格分隔提取结果,则可以使用如下命令。
awk -F: ‘{print $1 “” $3}’ /etc/passwd
案例4-2:在Shell脚本中定义变量并进行引用。
- #!/bin/sh
- var="hello itheima"
- echo $var
- echo "$var"
- echo '$var'
- exit 0
案例4-3:输入文件名,判断文件是否为目录,若是,则输出“[文件名]是个目录”。
- #!/bin/sh
- #单分支if语句
- read filename
- if [ -d $filename ]; then
- echo $filename" is a directory"
- fi
- exit 0
案例4-4:输入文件名,判断文件是否为目录,若是,则输出“[文件名]是个目录”;否则输
出“[文件名]不是目录”。
- #!/bin/sh
- #双分支if语句
- read filename
- if [ -d $filename ]; then
- echo $filename" is a directory"
- else
- echo $filename" is't a directory"
- fi
- exit 0
案例4-5:判断一个文件是否为目录,若是,输出目录中的文件;若不是,判断该文件是否可执行。若能执行,输出“这是一个可执行文件”;否则输出“该文件不可执行”。
- #!/bin/sh
- read filename
- if [ -d $filename ]; then
- ls $filename
- elif [ -x $filename ]; then
- echo "This is a executable file."
- else
- echo "This is not a executable file."
- fi
- exit 0
案例4-6:编写脚本,脚本可输出一个包含Android、Java、C++、IOS这四项的目录。脚本根据用户的选择,输出对应的内容,如Your have selected C++。
- #!/bin/sh
- #select条件语句
- echo "What do you want to study?"
- select subject in "Android" "Java" "C++" "IOS"
- do
- echo "You have selected $subject."
- break
- done
- exit 0
案例4-7:实现一个简单的四则运算,要求用户从键盘输入两个数据和一个运算符。脚本程序根据用户输入,输出计算结果。
- #!/bin/sh
- echo -e "a:\c"
- read a
- echo -e "b:\c"
- read b
- echo -e "select(+ - * /):\c"
- read var
- case $var in
- '+') echo "a+b="`expr $a "+" $b`;;
- "-") echo "a-b="`expr $a "-" $b`;;
- "*") echo "a*b="`expr $a "*" $b`;;
- "/") echo "a/b="`expr $a "/" $b`;;
- *) echo "error"
- esac
- exit 0
案例4-8:使用for循环输出月份列表中的12个月份。
- #!/bin/sh
- for month in Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
- do
- echo -e "$month\t\c"
- done
- echo
- exit 0
案例4-9:在当前目录的itheima文件夹中存放着多个以.bxg为后缀的文件,使用for循环将其中所有以.bxg结尾的文件删除。
- #!/bin/sh
- for file in ~/itheima/*.bxg
- do
- rm $file
- echo "$file has been deleted."
- done
- exit 0
-
案例4-10:使用while循环计算整数1~100的和。
- #!/bin/sh
- count=1
- sum=0
- while [ $count -le 100 ]
- do
- sum=`expr $sum + $count`
- count=`expr $count + 1`
- done
- echo "sum=$sum"
- exit 0
案例4-11:使用until循环输出有限个数据。
- #!/bin/sh
- #until
- i=1
- until [ $i -gt 3 ]
- do
- echo "the number is $i."
- i=`expr $i + 1`
- done
- exit 0
案例4-12:利用脚本case_test(4.4.4节中的案例4-7)测试-n选项的用法。
sh -n case_test
案例4-15:定义一个hello函数,该函数可以输出hello itheima,并在脚本中使用该函数。
- #!/bin/sh
- #function hello
- function hello(){
- echo "hello itheima."
- }
- #main
- hello #hello函数调用
- exit 0
案例4-16:分别为脚本中的位置变量和函数中的位置变量传参。
- #!/bin/sh
- #function
- function _choice(){
- echo "Your chioce is $1."
- }
- #main
- case $1 in
- "C++" ) _choice C++ ;;
- "Android" ) _choice Android ;;
- "Python" ) _choice Python;;
- *) echo "$0:please select in (C++/Android/Python)"
- esac
- exit 0
案例4-17:验证Shell脚本函数中定义的变量是否是局部变量。
- #!/bin/sh
- function fun(){
- a=10
- echo "fun:a=$a"
- }
- a=5
- echo "main:a=$a"
- fun #函数调用
- echo "main:a=$a"
- exit 0
案例4-18:使用local在函数中定义一个局部变量。
- #!/bin/sh
- function fun(){
- local a=10
- echo "fun:a=$a"
- }
- a=5
- echo "main:a=$a"
- fun #函数调用
- echo "main:a=$a"
- exit 0