Bash脚本
- 以
#!/bin/bash
为首行
参数
外部传参
test.sh
1 | #!/bin/bash |
$1 为第一个参数, $2 为第二个
用法: bash test.sh test1.sh
则$1被赋值为test.sh, $2被赋值为test1.sh
其他参数:
- $0 - 脚本名
zerotest.sh运行1
2#!/bin/bash
echo $0bash zerotest.sh
结果:
1 | zerotest.sh |
- $1 - $9 - 同上所述
- $# - 传入的参数个数
- $@ - 传入的所有参数
- $? - The exit status of the most recently run process.
- $$ - The process ID of the current script.
- $USER - The username of the user running the script.
- $HOSTNAME - The hostname of the machine the script is running on.
- $SECONDS - The number of seconds since the script was started.
- $RANDOM - Returns a different random number each time is it referred to.
- $LINENO - Returns the current line number in the Bash script.
内部定义
In:
1 | var=Hello |
Out:
1 | Hello |
- 还可以用一个执行块的返回结果作为参数的值
In:Out:1
2myvar=$( ls /etc | wc -l )
echo the value of myvar: $myvar1
the value of myvar: 87
不同脚本间传参
In:
script0.sh
1 | #!/bin/bash |
script1.sh
1 | #!/bin/bash |
Out:
1 | script0.sh :: var1 : blah, var2 : foo |
运行中输入参数
1 | read name |
计算相关
let
1 | #!/bin/bash |
expr
逻辑上差不多可以等同于 echo let, 注意格式
1 | #!/bin/bash |
$((计算语句))
1 | a=$((3+5)) # 无格式要求 |
${井号var}
输出var的长度(换成’#’markdown居然无法解析….)
语法
通过缩进确定码块作用域
if
1 | if [ <some test> ] |
switch
1 | case <variable> in |
while
1 | while [ <some test> ] |
until
1 | until [ <some test> ] |
while 和 until 的区别类似Java中的 while do 和 do while
for
1 | for var in <list> |
遍历文件夹下的所有文件: for i in $path/*; do
range
In:
1 | echo {1..5} |
Out:
1 | 1 2 3 4 5 |
select
In:
1 | select_example.sh |
1 | 1) Kyle 3) Stan |
常用前缀/比较符
Operator | Description |
---|---|
! EXPRESSION | The EXPRESSION is false. |
-n STRING | The length of STRING is greater than zero. |
-z STRING | The lengh of STRING is zero (ie it is empty). |
STRING1 = STRING2 | STRING1 is equal to STRING2 |
STRING1 != STRING2 | STRING1 is not equal to STRING2 |
INTEGER1 -eq INTEGER2 | INTEGER1 is numerically equal to INTEGER2 |
INTEGER1 -gt INTEGER2 | INTEGER1 is numerically greater than INTEGER2 |
INTEGER1 -lt INTEGER2 | INTEGER1 is numerically less than INTEGER2 |
-d FILE | FILE exists and is a directory. |
-e FILE | FILE exists. |
-r FILE | FILE exists and the read permission is granted. |
-s FILE | FILE exists and it’s size is greater than zero (ie. it is not empty). |
-w FILE | FILE exists and the write permission is granted. |
-x FILE | FILE exists and the execute permission is granted. |
note: 001 = 1 -> false; 001 -eq 1 -> ture
函数
函数必须定义在调用之前
两种定义方式:
1
2
3
4
5
6
7function_name () {
<commands>
}
function function_name{
<commands>
}如果需要传递参数, 直接:
In:1
2
3
4
5funcion_arvg{
echo $1
}
function_arvg HelloOut:
1
Hello
如果需要有返回值:
In:1
2
3
4
5
6function_return{
return 5
}
function_return
echo The funcion\'s return value is $?
Out:
1 | The funcion's return value is 5 |
函数未出现错误时默认返回值为0
作用域
In:
1 | #!/bin/bash |
Out:
1 | Before function call: var1 is global 1 : var2 is global 2 |