bash shell基础

来源:互联网 发布:php获取ip地理位置 编辑:程序博客网 时间:2024/06/07 23:52

1. 定义变量

指令:declare、typeset

declare -i num=1  #定义整形变量num,值为1

declare -r num=2 #定义只读变量num,值为2

declare -a arr='([0]="a" [1]="b" [3]="c")' #定义数组变量arr,读取:echo ${arr[0]}

declare -F #显示脚本中的函数

declare -f #显示脚本中的函数体


2. 将所跟参数作为shell的输入,并执行产生的指令

指令:eval

eval echo "hello world"  #输出 hello world


3. 执行命令取代当前shell

指令:exec

注:命令后的其他命令将不再执行

exec echo "hello world"  #输出hello world


4. 退出shell

指令:exit


5. 整数运算

指令:let

let i=2+2 #i=4


6. 从标准输入读取一行到变量

指令:read

read n #要求输入n的值,注意要先定义变量n


7. 函数返回值

指令:return

函数如下:

[root@localhost ~]# cat test.sh

#!/bin/bash

#定义函数

function test() {

return 1

}

#调用函数

test

#查看函数返回值

echo $?

脚本执行效果

[root@localhost ~]# bash test.sh

1



判断和循环的语法

判断:

1) if expression ; then statement  fi

2) if expression ; then statement1 else statement2 fi

3) if expression1 ; then statement1 elif expression2 ; then statement2 else statement3 fi

for循环:

1) for val in val1 val2 val3 do statement done

2) for ( ( expression1; expression2; expression3 ) ) do statement done

while循环

1) while expression do statement done

until循环

1) until expression do statement done

select循环(与用户有交互,且如果不限制只会无限循环)

1) select val in val1 val2 val3 do statement done

0 0