通过shell例子来学习循环结构的语法


心得: 所谓有用就是学会了一直在使用,不经常用叫没多大用,忘记了就叫没用。反过来想想经常挨领导批的很有可能是领导对你有很大的期望。所以我们学会的东西要经常用到实际中去才是自己的东西。

其实学习的最好方法就是先接触实际的东西,用实践来验证理论。

写脚本编写要求证,可以一边测试一边写(中间最好有个输出标记看到哪儿错了)。

下面的例子在林夕昱老师的视频里看到的,自己为了练习在CentOS的系统下默写下来了,可能是刚学吧,总是写下来执行后得到好多提示(当然了这些提示是错误信息的了,不过对我这个初学者挺有帮助的,希望初学者看过林老师的视频知道思路后一定要自己试着写下来练习才是)。在这里想通过自己看过视频后做个笔记吧,也是帮助自己更快进步。废话不说了,看例子吧

example 1:该脚本是让用户输入目录,然后脚本会先判断是不是目录或为空否,如是目录会先列出目录下的文件,然后一个一个判断文件的类型,在判断文件的权限。最后列出用户输入目录下的文件的类型和权限。

#!/bin/bash
#program:use for to display a directory's filetype and permission
#history:2013-02-20 ASK first release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

read -p "please you input a directory:" dir
if [ -z "$dir" -o ! -d "$dir" ]; then
echo "you have input nothing or $dir is NOT a directory"
exit 0
fi
filen=`ls $dir`
for filename in $filen
do
[ -c $dir/$filename ] && filetype="is character file"
[ -p $dir/$filename ] && filetype="is PIPE file"
[ -f $dir/$filename ] && filetype="is regular file"
[ -L $dir/$filename ] && filetype="is link file"
[ -S $dir/$filename ] && filetype="is sokkt file"
[ -d $dir/$filename ] && filetype="is directory"
[ -b $dir/$filename ] && filetype="is block file"

[ -r $dir/$filename ] && per="$per readable"
[ -w $dir/$filename ] && per="$per writeable"
[ -o $dir/$filename ] && per="$per executable"
[ -u $dir/$filename ] && per="$per set UID"
[ -g $dir/$filename ] && per="$per set GID"
[ -k $dir/$filename ] && per="$per set Sticky bit"

echo "this file $dir/$filename is $filetype ,and permission is $per "

filetype=""
per=""
done

  • 1
  • 2
  • 3
  • 下一页

相关内容