5

shell:脚本数组list的操作整理

 1 year ago
source link: https://blog.51cto.com/mouday/5867861
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

shell:脚本数组list的操作整理

精选 原创

彭世瑜 2022-11-18 10:40:04 ©著作权

文章标签 数组 bash 数组长度 文章分类 Java 编程语言 yyds干货盘点 阅读数224

# 定义数组,等号两边不要有空格
list=(
    "A"
    "B"
)

# 数组长度
echo ${#list[@]} # 2

# 获取数组元素
echo ${list[1]} # B

# 输出所有值
echo ${list[@]} # A B

# 循环打印数组
for var in ${list[@]}; do
    echo "var = ${var}"
done

# 输出:
# var = A
# var = B

字符串转数组

# 字符串转数组
str="A B C"

arr=($str) 

# 数组长度
echo ${#arr[@]} # 3

# 所有数组元素
echo ${arr[@]}
# A B C
# 字符串转数组
str="A,B,C"

arr=(`echo $str | tr ',' ' '`) 

# 数组长度
echo ${#arr[@]} # 3

# 所有数组元素
echo ${arr[@]}
# A B C

参考
 Shell脚本list史上最全教程

  • 打赏
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK