Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to understand linux shell array

Shulou Source: shulou.com Published: 2022-06-01 03:41:14 09月29日 Update

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

Tags: Array code character string variable element environment example application location content single parameter more standard knowledge reference help input output Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Redmi Xiaomi Shulou Information Docker