拓展閱讀
linux Shell 命令行-00-intro 入門介紹
linux Shell 命令行-02-var 變量
linux Shell 命令行-03-array 數(shù)組
linux Shell 命令行-04-operator 操作符
linux Shell 命令行-05-test 驗證是否符合條件
linux Shell 命令行-06-flow control 流程控制
linux Shell 命令行-07-func 函數(shù)
linux Shell 命令行-08-file include 文件包含
linux Shell 命令行-09-redirect 重定向
定義
Shell 僅支持單維數(shù)組。
array=(值1 值2 ... 值n)
- array.sh
#!/bin/sh
# 數(shù)組演示
array=(a b "c" d)
# 另一種定義數(shù)組的方式
array_two[0]=a
array_two[1]=b
array_two[2]="c"
array_two[3]=d
讀取
您可以這樣從數(shù)組中讀取:
${array_name[index]}
- read_array.sh
#!/bin/sh
# 從數(shù)組中讀取
array=(a b c "d")
echo "第一個元素是 ${array[0]}"
echo "第二個元素是 ${array[1]}"
echo "第三個元素是 ${array[2]}"
echo "最后一個元素是 ${array[-1]}"
- 運行
root@iZuf60ahcky4k4nfv470juZ:~/code/shell# chmod +x read_array.sh
root@iZuf60ahcky4k4nfv470juZ:~/code/shell# ./read_array.sh
第一個元素是 a
第二個元素是 b
第三個元素是 c
最后一個元素是 d
讀取所有元素
我們可以使用 *
或 @
來獲取數(shù)組中的所有元素。
- read_all_array.sh
#!/bin/sh
# 讀取數(shù)組中的所有元素
array=(a b c d)
echo "數(shù)組中的所有元素:${array[*]}"
echo "數(shù)組中的所有元素:${array[@]}"
- 運行
root@iZuf60ahcky4k4nfv470juZ:~/code/shell# chmod +x read_all_array.sh
root@iZuf60ahcky4k4nfv470juZ:~/code/shell# ./read_all_array.sh
數(shù)組中的所有元素:a b c d
數(shù)組中的所有元素:a b c d
數(shù)組長度
我們可以使用 ${#array[*]}
或 ${#array[@]}
來獲取數(shù)組的大小。
- array_length.sh
!#/bin/sh
# 數(shù)組長度
array=(a b c d E)
echo "數(shù)組的大小為:${#array[*]}"
echo "數(shù)組的大小為:${#array[@]}"
- 運行
root@iZuf60ahcky4k4nfv470juZ:~/code/shell# chmod +x array_length.sh
root@iZuf60ahcky4k4nfv470juZ:~/code/shell# ./array_length.sh
數(shù)組的大小為:5
數(shù)組的大小為:5
參考資料
https://www.runoob.com/linux/linux-shell.html文章來源:http://www.zghlxwxcb.cn/news/detail-838485.html
本文由博客一文多發(fā)平臺 OpenWrite 發(fā)布!文章來源地址http://www.zghlxwxcb.cn/news/detail-838485.html
到了這里,關(guān)于linux Shell 命令行-03-array Shell 數(shù)組的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!