shell有两种模式,一个sh,一个bash,如果想写shell代码,最好用sh格式,设置如下
把 #!/bin/sh 放在.sh文件的最开始
现在看一些简单应用:
- 变量
$符号是用来声明变量的
注意!!!!!!
a和=还有test和=之间不能有空格
a=test
echo $a
Output: test
如果一个变量的值是另外一个变量的名字,且想通过这个变量名取到另外一个变量的值,可用如下方法
a=b
b=test
echo ${!a}
Output: test
- array
see example:
tests = (a b c d)
echo ${#tests[@]}
echo ${tests[@]}
Output:
4
a b c d
- for loop
tests=(a b c d)
for i in ${tests[@]}
do
echo $i
done
Output:
a
b
c
d
for ((i=0;i<4;i++))
do
echo ${tests[$i]}
done
Output:
a
b
c
d
- if else
if [ “a” = “b” ] || [ “a” = “c” ]
then
echo “b or c equals c”
elif [ “a” = “a” ]
echo “a equals a”
else
echo “this is else”
fi
Ouput:
a equals a
- claim function
注意!!!!!
函数名和’{‘之间要有一个空格
function f {
a=$1
b=$2
echo $a
echo $b
}
f var1 var2
Output:
var1
var2
通过引入文件来调用方法
source filepath/f1.sh
f var1 var2
Output:
var1
var2
- shell的管道
env | grep sss
Output:
something contains string "sss"
这里env主要是获取环境变量
|把左边命令的结果作为右边命令的输入传递
grep有点类似正则表达式
这行命令主要是获取环境变量中包含字符sss的内容