当前位置:网站首页>shell记录

shell记录

2022-06-09 17:54:00 edycm

shell的一些用法记录

字符操作

#!/bin/bash

str="hello world, hello world"
echo ${
    #str} # 取长度, 输出: 24

echo ${str:2:3} # 截取字符串, 2: 开始位置, 3: 长度, 输出: llo
echo ${str:2:-1} # 截取字符串, 2: 开始位置, -1: 长度,表示到末尾, 输出: llo world, hello worl

echo ${str#he*o} # 从str开头, 删除第一个最短匹配的he*o, 输出: world, hello world
echo ${str##he*o} # 从str开头, 删除第一个最长匹配的he*o, 输出: rld

echo ${str%o*ld} # 从str末尾, 删除第一个最短匹配的he*o, 输出: hello world, hello w
echo ${str%%o*ld} # 从str末尾, 删除第一个最长匹配的he*o, 输出: hell

echo ${str/wo/we} # 替换第一个he为we, 输出: hello werld, hello world
echo ${str//wo/we} # 替换所有he为we, 输出: hello werld, hello werld

echo ${str/#he/we} # 如果字符串以he开头, 则将其替换为we, 输出wello world, hello world
echo ${str/%ld/le} # 如果字符串以ld结尾, 则将其替换为le, 输出hello world, hello worle

数组

#!/bin/bash

arr=(1 test)
arr[2]=2
arr[10]=ten

echo ${arr[0]} # 根据下标获取, 输出: 1
echo ${arr[10]} # 输出: ten

echo ${arr[@]} # 获取所有元素, 输出: 1 test 2 ten
echo ${arr[*]}

echo ${
    #arr[@]} # 获取长度, 输出: 4
echo ${
    #arr[*]}

for val in ${arr[@]} # 遍历数组元素, 输出: 1 test 2 len
do
    echo $val
done

for i in ${
    !arr[@]} # 遍历数组下表, 输出: 0 1 2 10
do
    echo $i
done

# 通过命令赋值到数组
file_list=(`ls`)
echo ${
    #file_list[@]}

map

#!/bin/bash

# 定义赋值
declare -A test_map=([1]="1" ["hello"]="world")
test_map[3]=1

# 取值
echo ${test_map[1]} # 输出: 1

# 遍历取值
for k in ${
    !test_map[@]}
do
    echo key: $k, value: ${test_map[$k]} # key: hello, value: world # key: 1, value: 1 # key: 3, value: 1
done

函数

函数返回值范围为[0, 255]

小于0会报错,大于255会返回0:

./test.sh: line 4: return: -1: invalid option
return: usage: return [n]
#!/bin/bash

function test_func(){
    
    echo "hello"
    echo "world"
    local var="test" # 只在该函数中使用的变量, 可以定义为局部
    return 0
}

val=(`test_func`)
echo $? # 输出: 0
echo ${val[@]} # 输出: hello world
echo $var # 输出: 

条件判断

一般使用test命令检查条件是否成立,也可使用中括号替代[]

可使用与( -a、&&)、或( -o 、||)、非( ! )逻辑操作符将测试条件连接起来,其优先级为: ! 最高, -a 次之, -o 最低

数值比较:

  • -eq 相等为真
  • -ne 不相等为真
  • -gt 大于为真
  • -ge 大于等于为真
  • -lt 小于为真
  • -le 小于等于为真
#!/bin/bash

if test 1 -eq 1 && test 2 -ge 1
then
    echo "1"
else
    echo "2"
fi

if [ 1 -eq 1 -a 2 -ge 1 -o 1 -lt 2 ] # if ((1 < 2)) && ((2 > 1)) # if [[ 2 > 1 ]] && [[ 1 < 2 ]] #
then
    echo "1"
else
    echo "2"
fi

字符串:

  • = 相等为真
  • != 不等为真
  • -z 字符串长度为0为真
  • -n 字符串长度不为0为真
#!/bin/bash

if test "h" = "i"
then
    echo "1"
else
    echo "2"
fi

文件:

  • -e 文件存在为真
  • -r 文件存在且可读为真
  • -w 文件存在且可写为真
  • -x 文件存在且可执行为真
  • -s 文件存在且至少有一个字符为真
  • -d 目录存在为真
  • -f 文件存在且为普通文件为真
  • -c 文件存在且为字符型特殊文件为真
  • -b 文件存在且为块特殊文件为真
#!/bin/bash

if test -d /bin
then
    echo "1"
else
    echo "2"
fi
原网站

版权声明
本文为[edycm]所创,转载请带上原文链接,感谢
https://blog.csdn.net/sinat_40658206/article/details/125006010