Reputation: 1487
I want to list all directories using a shell script. I am using the following code:
DIR="$1"
if [ $# -ne 1 ]
then
echo "Usage: $0 {dir-name}"
exit 1
fi
cd "$DIR"
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for user in $( ls -d */)
do
for dirs in $( ls -d $PWD/$user*)
do
echo $PWD/$user/$dirs;
done
done
IFS=$SAVEIFS
It is working for me if that directory don't have any spaces on it, else it split the output for every spaces on it. I got the following output:
abhinaba@abhinaba-desktop:~/software$ sh test.sh /media/2C44138344134F48/RB1
ls: cannot access /m: No such file or directory
ls: cannot access dia/2C44138344134F48/RB1/VB*: No such file or directory
ls: cannot access /m: No such file or directory
ls: cannot access dia/2C44138344134F48/RB1/DLI*: No such file or directory
ls: cannot access /m: No such file or directory
ls: cannot access dia/2C44138344134F48/RB1/3001/*: No such file or directory
ls: cannot access /m: No such file or directory
ls: cannot access dia/2C44138344134F48/RB1/VB*: No such file or directory
ls: cannot access /m: No such file or directory
ls: cannot access dia/2C44138344134F48/RB1/DLI*: No such file or directory
ls: cannot access /m: No such file or directory
ls: cannot access dia/2C44138344134F48/RB1/3002/*: No such file or directory
ls: cannot access /m: No such file or directory
ls: cannot access dia/2C44138344134F48/RB1/VB*: No such file or directory
ls: cannot access /m: No such file or directory
ls: cannot access dia/2C44138344134F48/RB1/DLI*: No such file or directory
ls: cannot access /m: No such file or directory
ls: cannot access dia/2C44138344134F48/RB1/3003/*: No such file or directory
Upvotes: 2
Views: 4994
Reputation: 10413
EDITED: removed ls
to optimize the script (from tripleee
)
If you use BASH shell:
#!/bin/bash
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
DIR="$1"
if [ $# -ne 1 ]
then
echo "Usage: $0 {dir-name}"
exit 1
fi
cd "$DIR"
for user in $(ls -d */)
do
for dirs in $(ls -d $user*)
do
echo $dirs
done
done
IFS=$SAVEIFS
Run the above "test.sh" script like this:
bash test.sh /media/2C44138344134F48/RB1
or simply (if you are already in BASH and you have set the eXecutable flag)
./test.sh /media/2C44138344134F48/RB1
Upvotes: 2
Reputation: 22252
It would actually be easiest to use find:
find PATH -type d -name '* *'
Or if you need to do something with each result, consider piping it to xargs
find PATH -type d -name '* *' -print0 | xargs -0 run-some-command
Or if you just want all the directories safely escaped into arguments then:
find PATH -type d -print0 | xargs -0 run-some-command
Inside run-some-command
, each argument to the script will be properly set to each directory name regardless of what characters it contains.
Upvotes: 2
Reputation: 10329
The simple script below will do what you need.
#!/bin/bash
function usage() {
echo "Usage: `basename $0` <dir-name>"
}
if [ "x$1" = "x" ]
then
usage
exit 0
fi
find "$1" -type 'd'
Upvotes: 0