在使用linux过程中,会经常用到 shell脚本, 整理了一些基本使用语法。
if…else
语法结构:
if 条件; then
操作
elif 条件; then
操作
else
操作
fi
案例如下:
[chenk@localhost ~]$ cat demo.sh
#!/bin/bash
# if ... else ...
if [[ "" == $1 ]] ; then
echo "You need send an arguement."
elif [ $1 == "exit" ]; then
echo "Exit" && exit 0
else
echo "The Argument is: $1"
fi
上述案例是if...else
的使用方法。判断条件[[ "" == $1 ]]
中,内层中括号前后都需留一个空格。
注: 在shell 脚本中, $0
表示脚本名称, $1
表示传入的第一个参数, $2
表示传入的第二个名称;比如上述脚本执行命令语句改成:
cat demo.sh arg1 arg2
那么 $0为 demo.sh, $1 为 arg1, $2为 arg2;
case
case语法:
case $var in
xx1) 操作
;;
xx2) 操作
;;
xx3) 操作
;;
*) 操作
;;
esac
上述 xx1-3
为 $var
的value值,如果不是xx1-3
里面的值,那么会进入 *
这个选项。
案例如下:
[chenk@localhost ~]$ cat demo2.sh
#!/bin/bash
# case $var in \n value) ...;; value2)...;; *)... ;; esac
case $1 in
"one") echo "Im one."
;;
"two") echo "Im two."
;;
"three") echo "Im three"
;;
*) echo "Im others."
;;
esac
注: ;;
操作后的 两个连续分号不能忘,并且两个分号是连续的,中间不能有空格;
函数
函数语法:
# 定义
function xx(){
操作
}
# 调用
xx()
案例如下:
[chenk@localhost ~]$ cat demo3.sh
#!/bin/bash
# case $var in \n value) ...;; value2)...;; *)... ;; esac
function prt(){
echo $1
case $1 in
"one") echo "Im one."
;;
"two") echo "Im two."
;;
"three") echo "Im three"
;;
*) echo "Im others."
;;
esac
}
echo "before function prt"
prt one
prt two
echo "after function prt"
在函数里面,如果有外部参数,函数内获取的方法也是 $1, $2…,不过需要区分函数的$1 与 脚本的$1是不同的。
while
while语法:
while 条件
do
操作
done
案例:
[chenk@localhost ~]$ cat demo4.sh
#!/bin/bash
# case $var in \n value) ...;; value2)...;; *)... ;; esac
function prt(){
echo "prt argument is $1"
case $1 in
"one") echo "Im one."
;;
"two") echo "Im two."
;;
"three") echo "Im three"
;;
*) echo "Im others."
;;
esac
}
echo "before function prt"
while read -p "please input arguement(input exit to exit):" arg && [ $arg != "exit" ]
do
prt $arg
done
echo "after function prt"
还有一个循环是 until, 不同的是:while是在条件成立时,进入循环;而until是在条件成立时,退出循环,其语法为:
until 条件
do
操作
done
for…in…
案例
[chenk@localhost ~]$ cat demo5.sh
#!/bin/bash
for file in `ls .`
do
echo $file
done
for num in one two three
do
echo $num
done
数组
定义一个数组,如下:
arr=("one" "two" "three" "four")
也可以这样定义:
array_name[0]=one"
array_name[1]="two"
array_name[2]="three"
array_name[3]="four"
使用数组:
# 整个数组
${arr[@]} 或者 ${arr[*]}
# 某个元素
${arr[index]}
数组长度:
${#arr[@]}
上述定义了一个四个元素的数组。元素间用空格分隔。
案例:
[chenk@localhost ~]$ arr=("one" "two" "three" "four")
[chenk@localhost ~]$ echo ${arr[0]}, ${arr[1]}, ${arr[2]}, ${arr[3]}
one, two, three, four
for循环
for循环语法:
for ((初始变量; 条件; 变量++))
案例:
[chenk@localhost ~]$ cat demo6.sh
#!/bin/bash
arr=("one" "two" "three" "four")
for ((i=0; i<${#arr[@]}; i++));
do
echo ${arr[i]}
done
上述 ${#arr[@]}
表示数组长度