Linux Shell总结

shell 学习总结

总览

变量

1.可用字母数字下划线,不能以数字开头
2.不能使用bash关键字
3.变量赋值=号两边不能有空格,如 age='18'
4.变量使用,用符号$
age='18'
echo age
echo ${age}
如果需要字符串可变量一起使用,可用花括号确认变量,如
skill='java'
echo "i am good at ${skill}Script"
这里应该是skill作为一个参数加上一个字符串
5.可用 readonly 变量名 来设置变量为只读
country='china'
readonly country
country='other'
这里会报错,因为contry已经设置为只读了
6.使用unset 变量名 来删除变量,删除后不可用,不可删除只读变量
country='england'
unset country

字符串

1.字符串的赋值可用单引号,双引号,或者不用
2.字符串连接
sport='basketball'
echo "i am good at playing ${sport}"
3.获取字符串长度 echo ${#sport}
4.截取字符串 echo ${sport:1:2}

数组

只有一维数组,下标从0开始
1.定义数组, 数组名=(v1 v2 v3 v4)
arr=('1' '2' '3')
arr[0]=4
2.读取数组 ${arr[n]},读取所有元素 ${arr[@]}
3.读取数组长度 ${#arr[*]} 或者 ${#arr[@]}

参数

平时我们使用sh shell.sh 命令时可以传递参数,空格隔开,使用时用$n来使用
$0表示文件名, $1是第一个参数

流程化

if

if [1==1];then   
    ehco 'true'   
fi

a=10
b=20
if [ $a == $b ]
then
   echo "a 等于 b"
elif [ $a -gt $b ]
then
   echo "a 大于 b"
elif [ $a -lt $b ]
then
   echo "a 小于 b"
else
   echo "没有符合的条件"
fi

for

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done
for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

while

while condition
do
    command
done
#!/bin/bash
int=1
while(( $int<=5 ))
do
    echo $int
    let "int++"
done

你可能感兴趣的:(Linux Shell总结)