Shell script

来源:互联网 发布:淘宝网购 编辑:程序博客网 时间:2024/04/30 11:43

==========================================================

Shell script 定义函数以及传递参数
EXEC()
{
  echo $1
}

#-------------
#   Begine
#-------------

EXEC "Hello Shell world"

执行这段程序的结果是会在终端上打印出来:Hello Shell World.

参数列表可以用 $1, $2...来获得。。 

 

==========================================================

 

bash命令在shell脚本中的作用真的是举足轻重啊,很有技巧的使用,可以解决很多实际问题

1. 统计包含的文件/目录的个数
find ./ -maxdepth 1 -type d -print | wc -l


2. 解压缩某个压缩文件中的某个文件到指定文件夹
   unzip -x one.zip onefile -d tmp_folder


3.显示zip文件的内容
  unzip -l one.zip


4. 去除文件中相同的行
   sort -u filename.txt

5. 用sed awk 配合着正则表达式作文本内容提取,替换等等

6. 在给定的全路径下获取文件名
   baesname /home/june/myfile.txt
   * 配合和字符串替换的是用可以得到文件的路径。

 

==========================================================

[3] 在shell中的字符串操作

1. 字符串替换
   sed格式: sed -e 's/***/+++/flag'
   use "***" replace "+++"

   Eg:
   sed -e 's/.*(/(.*/).java.*//1/p'
   用项1去替换搜索到的整行,达到了从翻编译过来的内容中找到类名

2. 批量替换字符串中的某个字符
   格式: ${string//substr/instead_str}
   Eg:
   TEST="com.june.www"
   TEST="${TEST//./_}"
   echo $TEST
   result: com_june_www

3. 取得字符串长度
   ${#string}

4. 字符串截取
   - 从变量$string的结尾删除最短匹配的substring
   string="june say hello june"
   after_str="${string%june}"
   echo $after_str
   results: june say hello
   - 按照index截取
   length=`expr ${#string}-1`
   substr=${string: 0 : $length}

5. 字符串比较
   ERROR_MSG=".* No such file"
   check="rm -r folder"
   len=`expr match "$check" "$ERROR_MSG"`
   if [ $len -eq 0 ]; then
     echo "Have"
   else
     echo "Not have"
   fi
  
   * 在这里len可以获取到匹配到的字符数量,如果等于零证明一点都不匹配,则文件存在

 ==========================================================

 [4] 判断文件目录是否存在

1. tools="/home/user/tools"
   if [ -e "$tools" ] 是否存在这个目录
   if [ ! -e "$tools" ] 是否不存在这个目录

2. if [ -e "$tools/*.txt" ]
   判断这个目录下是否存在txt文件

 ==========================================================

[5] shell的一些小技巧

1. Loop 文件夹中的文件
   * for picture in "/home/pictues"
       do
         echo "The name of this picture is $picture"
     done

   * for song in `ls /home/songs/*.mp3`
2. 条件组合判断
   if [ "$June" = "Girl" ] || [ "$June" != "6" ]
      
3. 从终端读入用户输入的信息
   read variable
   echo $variable
4. 在终端上打印带颜色的字
   echo -e "/033[31m ERROR: This is a red string!/033[0m"
   # 31是所显示颜色的代码,40几就是字体的背景

5. 将正在写入的文件内容同步显示到屏幕上,达到双重定位输出流的效果
touch tmp.txt
for i in 1, 2, 3
  do
    echo "Something" >> tmp.txt
    tail -nl -f tmp.txt
  done

6. 取变量中值的值
 eg: A="June" B="A" 通过B取得A中存的值
     eval tmp=/$$B
 result: tmp 是 "June"

Shell脚本的总结基本完毕。。从零开始写shell脚本还是挺有收获的学习了很多的东西,尤其是对Linux命令的活用。。

这两个星期在客户的review我的refine下,我人生的第一个shell脚本已经顺利交付。。人生中shell脚本的代码行也超过了1000行。。呵呵