How to understand linux shell array
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