Shell 基础知识和总结
调试脚本 ? 变量和其它语言一样Shell中也有变量,而且更简单,但有一些比较特殊的地方.
定义变量需要注意: = 两边不能加空格,当赋值语句包含空格时请加引号(单引号/双引号均可)比如: 1 variable_name="ghui‘s blog" Shell中的变量可以分为两种类型:
与其它语言一样局部变量的可见范围是代码块或函数内,全局变量在全局范围内可见.看个简单的例子: num=111 func1() { local num=222 echo $num } echo "before---$num" func1 echo "after---$num" 输出: before---111 222 after---111 使用变量使用一个定义过的变量,只要在变量名前面加$即可,如: name=ghui echo $name echo ${name} 在使用变量时还有一个地方需要注意,请看下面的例子: str=‘abc‘ echo "1 print $str" echo ‘2 print $str‘ 输出: print abc 2 print $str 即: 被双引号括起来的变量会发生变量替换,单引号不会 注释Shell中注释使用#,而且它不支持多行注释. 常用的字符串操作字符串拼接name="shell" sayHi="hello,"$name" !" sayHi2="hello,${name} !" echo $sayHi $sayHi2 注意: 上面说的单双引号引起的变量替换问题 获得字符串长度string="abcd" echo ${#string} 截取字符串str="hello shell" echo ${str:2} echo ${string:1:3} 更多关于字符串的操作可以看这个 if/else流程控制基本语法结构: if condition then do something elif condition then do something elif condition then do something else do something fi 其中,elif语句和else语句非必须的.看个例子: a=1 if [ $1=$a ] then echo "you input 1" elif [ $1=2 ] then echo "you input 2" else echo " you input $1" fi 很简单,不过这里有两个地方需要注意,如果某个条件下的执行体为空,则你就不能写这个条件 即下面这样会报错: if condition then #do nothing elif condition then # do nothing #or else #do nothing 另外, if [$a=$b] #or if [ $a=$b] #or if [$a=$b ] 只有这样 if test "2>3" then ... fi 和 if [ "2>3" ] then ... fi 除[]之外,shell语言中还有几种其它括号,比如: 单小括号/双小括号/双中括号/…,不同的括号有不同的用法,更多关于shell中,括号的用法可以看看这个 switch流程控制当条件较多时,可以选择使用switch语句,shell中的switch语句的写法和其它语言还是有些不同的,基本结构如下: case expression in pattern1) do something... ;; pattern2) do something... ;; pattern2) do something... ;; ... esac 看个例子: input=$1 case $input in 1 | 0) str="一or零";; 2) str="二";; 3) str="三";; *) str=$input;; esac echo "---$str" 这个例子会根据你执行此脚本时传入的参数不同在屏幕上输出不同的值,其中第一个case
for循环基本结构: for name [in list] do ... done 其中,[]括起来的 for file in *.txt do open $file done 遍历当前目录下的所有txt文件,并依次打开. while循环基本结构: while condition do do something... done 看个例子: i=0 while ((i do ((i++)) echo "i=$i" done 输出: NOTE: 你可能需要去了解一下 until循环基本结构 until condition do do something... done 看个例子: i=5 until ((i==0)) do ((i--)) echo "i=$i" done 输出: 跳出循环shell中也支持 函数要定义一个函数,可以使用下面两种形式: function funcname() { do something } 或者 funcname () { do something } 看个例子 add() { let "sum=$1+$2" return $sum } add $1 $2 echo "sum=$?" 输入 输出 其中, NOTE:
向脚本传递参数先shell脚本传递参数,非常简单,只需要在你执行命令的后面跟上即可,看个例子: echo "$# parameters"; echo "[email?protected]"; echo "$0" echo "$1" 输入: 输出: 2 parameters 11 22 test.sh 11 解释: ? ?================================= ? ? ? ? --------------------- ref:https://blog.csdn.net/nange_nice/article/details/76531824 ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |