apple
apple

Reputation: 127

unexplained string from bash loop

I have some file in the name of OBS_SURFACE1**, OBS_SURFACE101, OBS_SURFACE103. Yes, there indeed is a file named OBS_SURFACE1**, which I guess where the problem arise. I wrote a bash script which has:

for fil in ` ls OBS_DOMAIN1?? `
do
  echo "appending" $fil
done

The first value of fil will be OBS_SURFACE1** OBS_SURFACE101 OBS_SURFACE103, the second OBS_SURFACE101. While I expect the first to be OBS_SURFACE1**. If there is no OBS_SURFACE1** file, there would be no problem. Why is that then?

Upvotes: 0

Views: 36

Answers (2)

michael501
michael501

Reputation: 1482

yet another way of doing this :

echo appending OBS_DOMAIN1??

this will list all files , no loop needed.

Upvotes: 0

Tom Fenech
Tom Fenech

Reputation: 74605

Don't parse ls! It will only ever lead to problems. Use a glob instead:

for fil in OBS_DOMAIN1??
do
  echo "appending $fil"
done

The problem that you are experiencing stems from the fact that the output of ls contains *, which are being expanded by bash. Note that I have also quoted the whole string to be echoed, which protects against word splitting inside the loop. See the links provided in the comments above for more details on that.

As pointed out in the comments (thanks Charles), you may also want to enable nullglob before your loop like this: shopt -s nullglob. This will mean that if there are no files that match the pattern, the loop will not run at all, rather than running once with $fil taking the literal value OBS_DOMAIN1??. Another option would be to check whether the file exists in within the loop, for example using:

if [[ -e "$fil" ]]; then
  echo "appending $fil"
fi

or the more compact [[ -e "$fil" ]] && echo "appending $fil".

Upvotes: 3

Related Questions