Chinaunix

标题: 新手看招 Linux Shell编程简单一例 [打印本页]

作者: jiuzhuaxiong    时间: 2008-03-31 22:53
标题: 新手看招 Linux Shell编程简单一例

引言:本人学shell也有一段时间了,感觉学习shell和其他语言一样就是多练习程序。网上很多初学shell的朋友,一定为了找不到练习的程序而苦
恼,我整合一下学习shell过程中遇到的比较基础的练习题,希望能给初学shell的朋友一些启发。(呵呵也许不该叫整合,习惯说这个词了)
  例子没有先后顺序:每个例子可能有多种方法
  1.
在/home/codfei以及它的子目录中查找含有codfei的所有文件

[root@localhost Linuxos]# grep -rsn "codfei" /home/
/home/codfei/c/Unix_c/2:1:codfei::::::::::::::::::::::
/home/codfei/c/Unix_c/1:1:codfei::::::::::::::::::::::
Binary file /home/codfei/c/.charset.c.swp matches

[root@localhost Unix_c]# find /home/codfei/ -type f | while read i;do grep -n codfei $i && echo $i && echo -----;done
1:codfei::::::::::::::::::::::
/home/codfei/c/Unix_c/2
-----
1:codfei::::::::::::::::::::::
/home/codfei/c/Unix_c/1
-----
Binary file /home/codfei/c/.charset.c.swp matches
/home/codfei/c/.charset.c.swp
-----
  2.
设计一个Shell程序,在/userdata目录下建立50个目录,即user1~user50,并设置每个目录的权限为 rwxr-xr--
  方法一:
#!/bin/bash
#最简单,效率最高的办法
mkdir -p /userdata/{1..50} && chmod 754 /userdata/{1..50}
  方法二:
#!/bin/bash
#利用seq命令加while read结构
seq 1 50 | while read i;do
   mkdir -p /userdata/$i
   chmod 754 /userdata/$i
done
  方法三:
  用for或while循环
#!/bin/bash
i=0
while [ $i -lt 50 ];do
   let i=i+1
   mkdir -p /userdata/$i
   chmod 754 /userdata/$i
done

#!/bin/bash
for ((i=1;i=50;i++));do
   mkdir -p /userdata/$i
   chmod 754 /userdata/$i
done
  方法四:
#!/bin/sh
for D in user{1..50}
do
mkdir -m 754 -p $D
done
  3.

[color="#810081"]linux
系统中有个文件,文件名为ABC.txt。如何将当前的系统时间追加到此文件行首?
  三种方法:
echo -e "`date`\n`cat ABC.txt`" > ABC.txt
echo "`date | cat - ABC.txt`" > ABC.txt
sed -i "1i`date`" ABC.txt
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/63379/showart_513220.html
作者: 我是卖白菜的    时间: 2008-04-05 21:37
不错 支持一下 适合初学者练习




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2