Shell编程入门

Shell编程入门

一,变量赋值及算术运算

// 演示样例代码:

a=1
echo $a
let b=$a+1
echo $b
c=$[a+b]
echo $c
d=$[c*2]
echo $d
let e=d*2
echo $e
f=$[e%5]
echo $f


// 注意“=”号两边不能有空格
// 以上代码片段将输出:
1
2
3
6
12
2

二,数组

1,赋值

// 演示样例代码

declare -a arr1=(1 2 3 4)
echo ${arr1[0]}
arr2=("China" "Japan" "Korea")
echo ${arr2[0]}
arr3[0]=100
echo ${arr3[0]}


 

// 以上代码片段将输出:
1
China
100

2。遍历数组

// 演示样例代码

arr2=("China" "Japan" "Korea")
for v in ${arr2[@]};do
 echo ${v}
done



// 以上代码片段将输出:
China
Japan
Korea

// 注:${arr2[@]}中的@符号表示元素列表


三。条件推断

1。整数比較

-lt,小于
-le,小于等于
-eq。等于
-ge,大于等于
-gt,大于
-ne。不等于

// 演示样例代码:

a=1
b=2
if [ $a -lt $b ];then
 echo "a<b is true"
else
 echo "a<b is false"
fi
c=3
if [ $a -lt $b ] && [ $c -gt $b ];then
 echo "a<b && c>b is true"
else
 echo "a<b && c>b is false"
fi


 

// 以上代码片段将输出:
a<b is true
a<b && c>b is true


2。字符串比較

s1 = s2
s1 != s2
s1 > s2
s1 < s2
-n s1。s1不为null,长度大于零
-z s1。s1为null。长度为零

// 演示样例代码:

s1="China"
s2="China"
if [ $s1=$s2 ];then
 echo "s1=s2 is true"
else
 echo "s1=s2 is false"
fi


 

// 以上代码片段将输出:
s1=s2 is true


3,文件属性推断

-a file1 :file1 存在
-d file1 :file1存在并是一个文件夹
-e file1 :file1 存在,同-a
-f file1 :file1 存在而且是一个常规的文件(不是文件夹或者其它特殊类型文件)
-r file1 :有读的权限
-s file1 :文件存在且不为空
-w file1 :有写的权限
-x file1 :有运行的权限,或者对于文件夹有search的权限
-N file1 :在上次读取后,文件有修改
-O file1 :own所属的文件
-G file1 :group所属的文件
file1 -nt file2 :file1 比 file2 更新,以最后更新时间为准
file1 -ot file2 :file1 比 file2 更旧 ,以最后更新时间为准

// 演示样例代码:

if [ -d "/home" ];then
 echo "/home dir exists"
else
 echo "/home dir not exists"
fi


 

// 以上代码片段将输出:
s1=s2 is true
/home dir is exists


四,函数定义

函数參数示意:
$0:表示函数名称
$1:第1个參数
$2:第2个參数

// 演示样例代码:

a=1
function func1() {
 local b=2
 return $[a+b+$1]
}
func1 3
b=$?

echo $b;


 

// 以上代码片段将输出:
6

注意:
Shell语言函数返回值不同于传统语言,Shell中的返回值一般是指命令运行后的返回值,成功0,失败1。
以上演示样例代码中有return语句。说明函数自己定义了返回值。所以能够用 $?

查看这个返回值。
a为全局变量,b为局部变量。

原文地址:https://www.cnblogs.com/jhcelue/p/6940482.html