Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand linux shell array

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces you how to understand linux shell array, the content is very detailed, interested friends can refer to reference, I hope to help you.

To introduce you to the linux shell array related knowledge, and provides sufficient examples for reference.

Declare an array:

declare -a array

(In fact, you don't have to declare it, you can assign it directly to the variable in array mode, BASH knows that it is an array)

Array assignment:

(1) array=(var1 var2 var3 … varN)

(2) array=([0]=var1 [1]=var2 [2]=var3 … [n]=varN)

(3) array[0]=var1

arrya[1]=var2

array[n]=varN

Counting the number of array elements:

${#array[@]} or ${#array[*]}

BASH's special parameters @ and * both mean "extended positional parameters, starting with 1", but the form is slightly different, but it seems to be universal when used in arrays.

Reference array:

The copy code is as follows:

echo ${array[n]}

Traverse array:

The copy code is as follows:

filename=(ls)

for var in ${filename[@]};do

echo $var

done

Here are some examples of shell arrays.

1. Read n strings from "standard input", and save the strings entered each time in array.

The copy code is as follows:

#!/ bin/bash

i=0

n=5

while [ "$i" -lt $n ] ; do

echo "Please input strings …expr $i + 1"

read array[i]b=i]b=i]b={array[KaTeX parse error: Expected 'EOF', got '}' at position 3: i]}̲ echo "b"

i=expr $i + 1

done

2. Put the letters in the string into the array one by one and output them to "standard output".

The copy code is as follows:

#!/ bin/bash

chars='abcdefghijklmnopqrstuvwxyz'

for (( i=0; i

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report