Description: The subscript for an array in the shell defaults to the 0 start
1, put the string in the array, get its length
Copy Code code as follows:
#!/bin/bash
Str= "A B--n D"
Array= ($STR)
length=${#array [@]}
Echo $length
for ((i=0; i< $length; i++))
Todo
echo ${array[$i]}
Done
Execution results:
[Oracle@99bill-as9 array]$ SH length.sh
4
A
--n
D
2), print string:
Copy Code code as follows:
#!/bin/bash
Str= "a b C"
For I in $str
Todo
Echo $i
Done
Or:
#!/bin/bash
Str= "a b C"
Array= ($STR)
For ((i=0;i<${#array [@]};i++))
Todo
echo ${array[$i]}
Done
Execution results:
A
C
2. When the string is split with other characters
Copy Code code as follows:
#!/bin/bash
Str2= "A#b#c"
A= ($ (echo $str 2 | tr ' # ' | tr-s '))
length=${#a [@]}
for ((i=0; i< $length; i++))
Todo
echo ${a[$i]}
Done
#echo ${a[2]}
Execution results:
A
C
3, other operations of the array
Copy Code code as follows:
#!/bin/bash
Str= "A b--n dd"
Array= ($STR)
length=${#array [@]}
The first element of the array is the direct output of #ouput
Echo $array
#Use Subscript Way Access array accesses the elements of an element in a subscript way
Echo ${array[1]}
#Output the array output
Echo ${array[@]}
#Output in the array subscript for 3 the length of the element that is labeled 3 in the output array
Echo ${#array [3]}
#Output in the array subscript 1 to 3 element output array subscript 1 to 3
Echo ${array[@]:1:3}
#Output in the array subscript greater than 2 elements output array lower-than-2 element
Echo ${array[@]:2}
#Output in the array subscript less than 2 elements output array lower than 2 element
Echo ${array[@]::2}
Execution results:
A
A b--n DD
2
b--n DD
--n DD
A b
4, traversal access to a string (the default is separated by a space, when the string is separated by other delimiters can refer to 2)
Copy Code code as follows:
#!/bin/bash
Str= "a--m"
For I in $str
Todo
Echo $i
Done
Execution results:
A
--m
5. How to use Echo to output a string str= "-n". Because-n is an argument to echo, the general method of echo "$str" is not output.
Solutions can include:
Copy Code code as follows:
echo X$str | Sed ' s/^x//'
Echo-ne "$STR \ n"
Echo-e "$str \n\c"
printf "%s\n" $str (this can also be)