1

I am looping though a directory for a certain command; however, I do not know how to accommodate for spaces

#!/bin/bash

image=(`ls *.bmp *.jpeg *.jpg | sort`)
data=(`ls *.dat | sort`)

for ((i=0; i < ${#image[@]}; i++))
do
  echo ${image[$i]} ${data[$i]}
done

I ran this script and it returned

OIS032_OS.bmp Disc
OIS034_OS.bmp Cube
OIS035_OD.bmp 200x200_9-30-2010_OD
OIS035_OS.bmp _ILM_RNFLOb.dat
OIS036_OD.bmp OIS007_Optic
OIS036_OS.bmp Disc

I wanted the program to return this line

OIS016_OD.bmp  OIS016_Optic Disc Cube 200x200_OS _ILM_RNFLOb.dat 

How do I fix bash array to store what I need

data=(`ls *.dat | sort`) 

2 Answers 2

6

Don't call ls; just use pattern matching to populate the array:

shopt -s extglob    # We'll use a more complicated glob to avoid needing to sort
image=( *.@(bmp|jpeg|jpg) )
data=( *.dat )

for ((i=0; i < ${#image[@]}; i++))
do
  echo ${image[$i]} ${data[$i]}
done
4
  • Thank You for your answer. I feeling little off today-added this line because stack overflow mininum character comment Commented Sep 7, 2012 at 18:44
  • 2
    Without requiring extglob, you can use brace expansion: image=( *.{bmp,jpeg,jpg} ) Commented Sep 8, 2012 at 0:44
  • 1
    Compare a=(*.{bmp,jpeg,jpg}) and b=(*.@(bmp|jpeg|jpg)) for the three files a.bmp, a.jpeg, and z.jpeg. I used the extended pattern to mimic the sorting shown in the original question, while the brace expansion would result in 3 separate patterns that would undergo filename expansion separately.
    – chepner
    Commented Sep 8, 2012 at 5:06
  • Thank you guys. I for explaining the complexities of bash. I will always use it to help write my scripts. I am wondering why I am saying thank you twice Commented Sep 21, 2012 at 18:57
1

I believe but am not certain you can do what you want with readarray and MAPFILE.

I asked something similar like this: Bash declaratively defining a list to loop on

Here another similar answer link: https://stackoverflow.com/a/7220619/318174

Not the answer you're looking for? Browse other questions tagged or ask your own question.