shell编程基础

(1)它必须以例如以下行開始(必须放在文件的第一行):
      # !/bin/sh
符号#!用来告诉系统运行该脚本的程序,本例使用/bin/sh。编辑结束并保存后,假设要运行该脚本,必须先使其可运行:
      chmod +x filename
此后在该脚本所在文件夹下,输入 ./filename 就可以运行该脚本。
(2)变量赋值和引用。Shell编程中,使用变量无需事先声明,须要给变量赋值时,能够这么写:  变量名=值 。
要取用一个变量的值,仅仅需在变量名前面加一个$ ( 注意: 给变量赋值的时候,不能在"="两边留空格 ) 
      # 对字符串变量赋值:
      a="hello world"  
      # 打印字符串变量a的值:
      echo "A is:" $a
运行结果:A is: hello world

     假设是变量不用输出到终端,直接在sh文件内部调用,使用单引號就可以:

       PRODUCT='real6410'

调用到的地方使用:

      mkdir -p out/target/product/$PRODUCT/obj/lib
(3)if 语句。"if"表达式假设条件为真,则运行then后的部分:
       if ....; then
       ....
       elif ....; then
       ....
       else
       ....
       fi
通经常使用" [ ] "来表示条件測试,注意这里的空格非常重要,要确保方括号前后的空格。比如:
[ -f "somefile" ] :推断是否是一个文件
[ -x "/bin/ls" ] :推断/bin/ls是否存在并有可运行权限
[ -n "$var" ] :推断$var变量是否有值
[ "$a" = "$b" ] :推断$a和$b是否相等

(4)循环。
while ...; do
   ....
done
仅仅要測试表达式条件为真,则while循环将一直执行。keyword"break"用来跳出循环,而keyword”continue”则能够跳过一个循环的余下部分,直接跳到下一次循环中。

(5)函数功能

       在sh中能够定义某段类似于函数的集成语句段,在名字前使用function申明。方法如:

function real6410_prebuild()
{
      mkdir -p out/target/product/$PRODUCT/obj/lib
      mkdir -p out/target/product/$PRODUCT/system/lib
     cp vendor/realarm/real6410/*.so out/target/product/$PRODUCT/obj/lib
     cp vendor/realarm/real6410/*.so out/target/product/$PRODUCT/system/lib
}

之后,在其它地方直接使用real6410_prebuild即可了。

(6)sync

同步文件句柄, 刷新全部未写入硬盘的数据。

(7)实例,可运行脚本update的内容例如以下。

#!/bin/bash
if [ "$1" = "" ]; then
	echo "Please input resolution,"
	echo "Such as: qvga, wqvga, wvga, hvga"
	exit
fi
p=$1
./tool/bmp_to_raw ./temp0.raw ./$p/"${p}_uboot".bmp
./tool/bmp_to_raw ./temp1.raw ./$p/"${p}_battery00".bmp
./tool/bmp_to_raw ./temp2.raw ./$p/"${p}_battery02".bmp
./tool/bmp_to_raw ./temp3.raw ./$p/"${p}_battery04".bmp
./tool/bmp_to_raw ./temp4.raw ./$p/"${p}_battery06".bmp
./tool/bmp_to_raw ./temp5.raw ./$p/"${p}_battery08".bmp
./tool/bmp_to_raw ./temp6.raw ./$p/"${p}_low_battery1".bmp
./tool/bmp_to_raw ./temp7.raw ./$p/"${p}_low_battery2".bmp
./tool/bmp_to_raw ./temp8.raw ./$p/"${p}_batteryfull".bmp
./tool/bmp_to_raw ./temp9.raw ./$p/"${p}_charger_ov".bmp
./tool/bmp_to_raw ./boot_logo ./$p/"${p}_kernel".bmp
./tool/zpipe -l 9 ./"${p}.raw" temp0.raw temp1.raw temp2.raw temp3.raw temp4.raw temp5.raw temp6.raw temp7.raw temp8.raw temp9.raw
rm -rf ./temp0.raw ./temp1.raw ./temp2.raw ./temp3.raw ./temp4.raw ./temp5.raw ./temp6.raw ./temp7.raw ./temp8.raw ./temp9.raw ./bootlogo.raw
echo "conversion finished"

      说明:$1表示第一个參数;以上命令依次运行。运行时用./update xxx就能够运行,可是还有些时候的shell脚本是用. 或者source来运行的,这些脚本是须要在当前shell环境下运行的(不会创建子进程),也即包括内建命令的脚本。


參考原文:http://bbs.chinaunix.net/thread-2231835-1-1.html

posted @ 2014-07-10 12:52  mfrbuaa  阅读(212)  评论(0编辑  收藏  举报