linux鸟哥私房菜学习笔记之四-script

来源:互联网 发布:淘宝申请实拍保护 编辑:程序博客网 时间:2024/06/04 17:52

一、格式

1.第一行声明使用的shell名称  例如 #!/bin/bash

2.shell里的指令是从左往右,从上到下顺序执行的,

3.参数间的多个空格符将被忽略掉,空白行也被忽略掉

4.内容太多可以用 \+回车 延伸到下一行继续

5.#为注释符号

二、source script和sh script和./script 执行的区别

上面三种命令,都可以执行shell但是有区别的

1)利用sh script或者./script执行script时候,会另起一个子程序来执行这个script,这样的话,script中用的变量,并不会在父程序中生效

2)利用source script 执行script的时候,script不会起子程序,而是自己去执行

测试代码:

#!/bin/bash                                                                 read -p"input var:" varecho "var is:" $var

运用 source运行

lizo@ubuntu:~/test$ unset varlizo@ubuntu:~/test$ source test.shinput var:lizovar is: lizolizo@ubuntu:~/test$ echo $varlizo

用 sh命令

lizo@ubuntu:~/test$ unset varlizo@ubuntu:~/test$ echo $varlizo@ubuntu:~/test$ sh test.sh input var:lizovar is: lizolizo@ubuntu:~/test$ echo $var



三、test

利用test命令可以检查文件极其相关的属性

常用的参数  

-e 是否存在

-f 是否为文件

-d 是否为文件夹


(这里用逻辑“或”和“与”来理解,如果test为1(true)的话,由于echo肯定为1(true)的,所以会执行前面的echo,因为“或”有一个为true的话,后面就不会执行了,都为true)

四、[]  

用于判断里面的条件

#!/bin/bash                                                                     read -p "input(y/n):" yn[ "$yn"= "y" ]&& echo"yes" || echo "no"

结果

lizo@ubuntu:~/test$ sh test.sh input(y/n):yyeslizo@ubuntu:~/test$ sh test.sh input(y/n):nno

注意上面的格式 如果用"_"来表示空格  [_"$yn"_=_"y"_]



五、script 默认参数

1)在script 后面写多个用空格分开的字符串,可以作为该script的参数来看待

2)在script中用 $1,$2.....来表示对应的参数,($0 表示执行script文件名)

3)$#表示参数的个数,$@表示参数的内容(除开$0) ,

测试代码:

#!/bin/bash                                                                     echo "parameter number:" $#echo "parameter content" $@echo "script file:" $0echo "parameter one:" $1

结果

lizo@ubuntu:~/test$ sh test.sh one two three fourparameter number: 4parameter content one two three fourscript file: test.shparameter one: one



六、条件判断语句

1、 if...then...

格式为

if [条件];then

条件满足执行

fi




这里有几点要注意  如果用_来表示空格的话

if_[_"$yn"_=_"y"_] 这里是要加空格的,不然会报错

复杂的逻辑:

if [ 条件1];then

条件1成立执行

elif [ 条件 2];

条件1不成立,条件2成立执行

else

上述条件都不成立执行

fi

2. case

1)格式

case 变量 in

内容1)

当变量为 内容1的时候执行

;;

内容2)

当变量为内容2的时候执行

;;

* )   #类似于 swich中的 default功能,即

上述都不满足时候执行

;;

esac


运行结果


3.while 循环

1)while循环

while [条件]

do

条件真执行

done

2)until [条件]

do

条件不为真执行

done

4、for 循环

格式

for (( 初始值:条件:步长 ))

do

程序

done

七、函数功能

1)函数定义

function 函数名(){

函数内容

}

函数的变量也是用$0,$1表示,$0表示函数名

8.script的追踪和debug

sh -n 不执行,仅检查语法

sh -v 执行前,输出script内容

sh -x 将使用的script语句输出

0 0
原创粉丝点击