Shell Script Programming Syntax:
Note:
Article source http://www.cnblogs.com/yunquan/p/6821850.html
Video Source: https://www.bilibili.com/video/av10565321/index_1.html?t=684
Each statement here must have a space control, or syntax error 1. file format
以.sh后缀 在文件里,第一行写环境变量 #!/bin/bashPATH = /usr/local/sbin:/usr/local/bin:/usr/sbin ....//保证在其他电脑,也能运行(这里是配置环境)export PATHexit 0 (=C语言return 0,可以省略)跳出,不继续向下执行
2. Execute SH
1)bash .sh文件 2)./.sh文件 3)source .sh文件
3.read
read -p(提示字符) "请输入你的名字" name(变量)echo "hello" $name
4. Judging type
** test命令: -e 该【档名】是否【存在】 (exist)?(常用) -f 该【档名】是否是【档案】(file)?(常用) -d 该【文件名】是否为【目录】(directory)?(常用)** -r 侦测该档名是否是具有【可读】属性? -w 侦测该档名是否是具有【可写】属性? -x 侦测该档名是否是具有【可执行】属性? -eq 两数相等(equal0) -ne 两数值不相等(not equal) -gt n1 > n2 (greater than) -lt n1 < n2 (less than) -ge n1 >= n2(greater than or equal) -le n1 <= n2(less than or equal)
eg
#!/bin/bash PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games export PATH read -p "请输入(Y/N):" yn [ "$yn" == "Y" -o "$yn" == "y" ] && echo "ok,continue" && exit 0 [ "$yn" == "N" -o "$yn" == "n" ] && echo "oh,intsdsd" && exit 0 echo "我不信这个也能出来" && exit 0
Default variables for shell scripts ($ $)
This is easy to understand, the script name is $ A and then the first parameter is the second argument is $ ... And so on
Okay, let's take a simple example.
$ A is the first argument, the following-n argument is empty, is false on the execution, is really executed after the statement, the last Exit
[ -n "$1" ] && echo "第一个参数是: $1" || exit 0[ -n "$2" ] && echo "第二个参数是: $2" || exit 0
5. Conditional-judging if ... then
if [];then ......elif [];then ......else ...... fi(结束语)exit 0
eg
#!/bin/bashPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/gamesexport PATHread -p "请输入(Y/N):" ynif [ "$yn" == "Y" -o "$yn" == "y" ];then echo "ok,continue"elif [ "$yn" == "N" -o "$yn" == "n" ];then echo "oh,intsdsd" else echo "我不信这个也能出来" fiexit 0
Case ... Esac
#!/bin/bashcase $1 in "hello") echo "hello,how are you" ;; "") echo "你必须输入参数" ;; *) echo "要输入hello啊" ;;esac
function functions
#!/bin/bashfunction h(){ echo "好帅啊 $1" //function函数也有变量,$1就是函数的参数,这个和脚本的变量不同}case $1(脚本的第一个参数,从bash外面输入的) in "one") h 1 ;; "two") h 2 ;; "three") h 3 ;; *) echo "只能用123" ;; esac
Loopwhile do
#!/bin/bashread -p "请输入一个数字:" numberi=0s=0while [ "$i" -lt "$number" ] //这里的小于号是 -lt 注意!doi=$(($i+1)) //这里为什么要两个()?因为()有运算的意思s=$(($s+$i)) //这里i和s这两行不能有空格,否则失败doneecho -e "‘1+2+...+$number‘ 的结果是: $s "
6.shell Script Tracking and debug
-n 不执行script,仅查询语法问题: -v 执行script前,先将script 的内容输出到屏幕上 -x 将使用到的script内容显示到屏幕上,这是很有用的参数
Shell script Programming Basic syntax: