# linux命令行
# bash shell学习
# shell脚本
- shell脚本是一个可执行文件。
- exit 可以中断shell的执行。
- $?可以查看shell执行的结果。
# 变量定义
- 变量定义的格式
key=value;
要注意等号中间不能有空格;- 局部变量作用于函数内,用
local
修饰:local key=value;
# 变量的使用
变量的使用格式有几种:
$key,${key}
,如果是字符串变量,最好加双引号:"$key", "${key}"
。
# 函数定义
- 函数定义有两种格式,一种是用function关键词,一种是用()。
- 格式1:
function fn_name { ... }
- 格式2:
fn_name() { ... }
- 一个shell脚本就是一个函数,函数可以篏套定义。以及互相调用。
function <name> {
command1
command2
...
return
}
OR
<name>() {
command1
command2
...
return
}
# 函数参数
- 函数带参数式调用:
fn_name ${param1} ${param2}
$#
参数个数$*
把所有参数当作一个参数,相当于用双引号把所有参数引起来,等于"$1 $2 ... $n"
形式输出所有参数,结合括号($*)
以数组形式读取。$$
脚本运行的当前进程ID号$!
后台运行的最后一个进程的ID号$@
与$*类似,但是使用时加引号,并在引号中返回每个参数,等于"$1" "$2" ... "$n"
形式输出所有参数$-
显示shell使用的当前选项,与set命令功能相同。$?
显示最后命令的退出状态。0表示没有错误,其它值表明有错误。
# 测试(test命令)
- 格式:
#执行结果为true(0)或false(1) #古老的格式 test expression #古老的格式 [ expression ] #或 [[ expression ]] #适用所有直观表达式,推荐使用。 #或整型专属expression使用直观的数学表达式。 ((expression))
- 可以用
echo $?
来打印执行结果
# 整型表达式
符号
-eq -ne -le -ge -lt -gt
(( 数学表达式 ))
eg1:
test num1 -eq num2
eg2:
[ num1 -eq num2 ]
eg3:
[[ num1 -eq num2 ]]
eg4:
((num1>num2 || num3<num4))
#!/usr/bin/env bash max1() { local a=$1 local b=$2 if test $a -gt $b; then echo "max1:a($a) is bigger then b($b)." else echo "max1:a($a) is smaller then b($b)." fi } max2() { local a=$1 local b=$2 if [ $a -gt $b ]; then echo "max2:a($a) is bigger then b($b)." else echo "max2:a($a) is smaller then b($b)." fi } max3() { local a=$1 local b=$2 if [[ $a -gt $b ]]; then echo "max3:a($a) is bigger then b($b)." else echo "max3:a($a) is smaller then b($b)." fi } max4() { local a=$1 local b=$2 if (($a > $b)); then echo "max4:a($a) is bigger then b($b)." else echo "max4:a($a) is smaller then b($b)." fi } max1 $RANDOM $RANDOM max2 $RANDOM $RANDOM max3 $RANDOM $RANDOM max4 $RANDOM $RANDOM
# 字符串表达式
表达式 | 如果为真 |
---|---|
string | string 不为 null。 |
-n string | 字符串string的长度大于0。 |
-z string | 字符串string的长度为0。 |
string1 = string2 string1 == string2 | string1和string2相同。单或双等号都可以,建议用双等号。 |
string1 != string2 | string1和string2不相同。 |
string1 > string2 | string1排列在string2之后。 |
string1 < string2 | string1排列在string2之前。 |
<和>操作符使用test或[]要用引号引起来或反斜杠转义,或使用[[]]这个就可以按直观的数学表达式使用
# 文件表达式
表达式 | 如果为真 |
---|---|
file1 -ef file2 | file1和file2拥有相同的索引号(通过硬链接两个文件名指向相同的文件)。 |
file1 -nt file2 | file1新于file2。 |
file1 -ot file2 | file1早于file2。 |
-b file | file存在并且是一个普通文件。 |
-c file | file存在并且是一个字符(设备)文件。 |
-d file | file存在并且是一个目录。 |
-e file | file存在。 |
-f file | file存在并且是一个普通文件。 |
-g file | file存在且设置了组ID. |
-G file | file存在并且由有效组ID拥有。 |
-k file | file存在并且设置了它的"sticky bit"。 |
-L file | file存在并且是一个符号链接。 |
-O file | file存在并且由有效用户ID拥有。 |
-p file | file 存在并且是一个命名管道。 |
-r file | file存在并且可读(有效用户有可读权限)。 |
-s | file存在并且其长度大于0。 |
-S file | file存在并且是一个网络socket。 |
-t fd | fd是一个定向到终端/从终端定向的文件描述符。这可以被用来决定是否重定向了标准输入/输出错误。 |
-u file | file存在并且设置了setuid位。 |
-w file | file存在并且可写(有效用户拥有可写权限)。 |
-x file | file存在并且可执行(有效用户有执行/搜索权限)。 |