Shell数组和字典总结

2022-07-20  本文已影响0人  阿当运维

一. 数组

1.1 创建数组

names=()


names=()

declare -p names

declare -a names=()

names+="beijing"

declare -p names

declare -a names=([0]="beijing")

names+=("beijing" "shanghai" "guangzhou")

declare -p names

declare -a names=([0]="beijing" [1]="beijing" [2]="shanghai" [3]="guangzhou")

names=("Bob" "Peter" "$USER" "Big Bad John")

names=([0]="Bob" [1]="Peter" [20]="$USER" [21]="Big Bad John")

names[0]="Bob"

photos=(~/"My Photos"/*.jpg)

files=(*)

declare -a myfiles='([0]="/home/a/.bashrc" [1]="billing codes.xlsx" [2]="hello.c")'


names=(beijing shanghai)

ages=(19 20 99)

etcs=(${names[@]} ${ages[@]})

declare -p etcs

declare -a etcs=([0]="beijing" [1]="shanghai" [2]="19" [3]="20" [4]="99")


# 精确匹配

names=(beijing shanghai)

new_names=(${names[@]/hai/guangzhou})

declare -p new_names

declare -a new_names=([0]="beijing" [1]="shangguangzhou")

# 模糊匹配

names=(beijing shanghai)

new_names=(${names[@]/*hai/guangzhou})

declare -p new_names

declare -a new_names=([0]="beijing" [1]="guangzhou")

1.2 访问数组


char=(a b c q w x y z)

echo "${char[2]}"

c


# 表示从下标为3的位置开始访问2个元素

arr=(able good fly python java test go now)

echo "${arr[@]:3:2}"

python java


arr=(able good fly python java test go now)

echo "${#arr[3]}"

6

1.3 遍历数组

declare -p myfiles

printf '%s\n' "${myfiles[@]}"


for file in "${myfiles[@]}"

do

cp "$file" /backups/

done


myfiles=(db.sql home.tbz2 etc.tbz2)

cp "${myfiles[@]}" /backups/


names=("Bob" "Peter" "$USER" "Big Bad John")

echo "Today's contestants are: ${names[*]}"

Today's contestants are: Bob Peter lhunath Big Bad John


$ array=(a b c)

$ echo ${#array[@]}

3

declare -a myfiles='([0]=".bashrc" [1]="billing codes.xlsx" [4]="hello.c")'

echo ${#myfiles[@]}

3


$ first=(Jessica Sue Peter)

$ last=(Jones Storm Parker)

for i in "${!first[@]}"; do

echo "${first[i]} ${last[i]}"

done

结果

Jessica Jones

Sue Storm

Peter Parker


char=(a b c q w x y z)

for ((i=0; i

echo "${char[i]} and ${char[i+1]}"

done

结果

a and b

c and q

w and x

y and z

1.4 删除元素


char=(a b c q w x y z)

declare -p char

declare -a char=([0]="a" [1]="b" [2]="c" [3]="q" [4]="w" [5]="x" [6]="y" [7]="z")

unset char[2]

declare -p char

declare -a char=([0]="a" [1]="b" [3]="q" [4]="w" [5]="x" [6]="y" [7]="z")

二. 字典

bash里面的字典叫做关联数组,字典其实和数组类似,不同点在于,字典的key是字符串,并且遍历时是随机的。

注意事项:

2.1 创建字典


declare -A fullNames

fullNames=( ["lhunath"]="Maarten Billemont" ["greycat"]="Greg Wooledge" )

echo "I'am ${fullNames[greycat]}."


$ declare -A dict

$ dict[astro]="Foo Bar"

$ declare -p dict

declare -A dict='([astro]="Foo Bar")'

2.2 遍历字典


for user in "${!fullNames[@]}"; do

echo "User: $user, full name: ${fullNames[$user]}."

done

User: lhunath, full name: Maarten Billemont.

User: greycat, full name: Greg Wooledge.

三. 总结

上一篇 下一篇

猜你喜欢

热点阅读