Tuesday, May 7, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  0] [ 0]  / answers: 1 / hits: 1265  / 3 Years ago, sat, october 30, 2021, 2:14:02

I encounter an issue running a basic script listing directories.



for item in *
do
if [ -d $item ]
then
echo $item
fi
done


The outcome:




  1. lists all system folders

  2. returns an error: for.sh: 4: [: discover: unexpected operator

  3. lists all my folders, whose names start from a lowercase character



My guess is -d finds some issue with an initial lowercase character?
Can somebody please explain why it happens? Thanks a lot in advance.


More From » bash

 Answers
2

Some directories/files may contain spaces in their names, this would cause the error you are getting. So use quotes:



for item in *
do
if [ -d "$item" ]
then
echo "$item"
fi
done


if you want them sorted alphabetically use



for item in *
do
if [ -d "$item" ]
then
echo "$item"
fi
done | sort





As an example of the issue, suppose a file is called My File. If you don't use quotes you would get (after bash expansion)



if [ -d My File ]


so it is like "Test: Is My a directory? Do File", but File is not a valid test operator, thus the error.


[#30139] Saturday, October 30, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
splenueak

Total Points: 448
Total Questions: 118
Total Answers: 110

Location: Vanuatu
Member since Mon, Oct 3, 2022
2 Years ago
;