Recently I found in Bash some new syntax that was useful for me. I describe it here.
Make an array from a list returned by a command
If you capture the output of a command that usually prints a list on the standard output you don't get an array but a string with the list items delimited by a blank character. To transform this output into an array you have to surrond the "capturing" expression with another pair of brackets:
sites=($(find /srv -maxdepth 3 -type f -name "node_server.cfg"))
Array length
To get all the items in an array you can use the "@" or "*" character in place of the array index:
ports=${PORTLIST[@]}
Now, if you add a "#" character in front of the array name you get the array length:
portlistlen=${#PORTLIST[@]}
Another syntax for the "for" cycle
The "for" cycle accepts, besides the usual "for a in ..." syntax, another syntax more similar to that of the C language:
for (( i=0; i<$portlistlen; i++ ))
do
...
done
Make an array from a list returned by a command
If you capture the output of a command that usually prints a list on the standard output you don't get an array but a string with the list items delimited by a blank character. To transform this output into an array you have to surrond the "capturing" expression with another pair of brackets:
sites=($(find /srv -maxdepth 3 -type f -name "node_server.cfg"))
Array length
To get all the items in an array you can use the "@" or "*" character in place of the array index:
ports=${PORTLIST[@]}
Now, if you add a "#" character in front of the array name you get the array length:
portlistlen=${#PORTLIST[@]}
Another syntax for the "for" cycle
The "for" cycle accepts, besides the usual "for a in ..." syntax, another syntax more similar to that of the C language:
for (( i=0; i<$portlistlen; i++ ))
do
...
done
Comments
Post a Comment