Tuesday, 5 February 2008

Storing results of commands in an array

If you want to create an array of directories using bash you might try:

directories=`ls`

However, this will create a variable containing each file separated by spaces like this:
adm agentx cache games lib lock log mail opt run spool tmp X11R6 yp
To place each item into its own element you simply need to add some brackets:

directories=(`ls`)

You can test this has worked with a simple loop:

directories=(`ls /var`)
for (( i=0; i<${#directories[@]}; i+=1 )); do echo ${directories[${i}]} ; done
output:
adm
agentx
cache
games
lib
lock
log
mail
opt
run
spool
tmp
X11R6
yp

No comments:

Post a Comment