我想使用shell脚本列出所有目录。我使用以下代码:
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
如果该目录上没有任何空格,它对我有用,否则它会为其上的每个空格分割输出。我得到了以下输出:
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
答案 0 :(得分:2)
已编辑:已移除ls
以优化脚本(来自tripleee
)
如果你使用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
运行上面的“test.sh”脚本,如下所示:
bash test.sh /media/2C44138344134F48/RB1
或简单地(如果您已经在BASH中并且已设置了eXecutable标志)
./test.sh /media/2C44138344134F48/RB1
答案 1 :(得分:1)
使用find实际上最简单:
find PATH -type d -name '* *'
或者,如果您需要对每个结果执行某些操作,请考虑将其连接到xargs
find PATH -type d -name '* *' -print0 | xargs -0 run-some-command
或者,如果您只是希望所有目录安全地转义为参数,那么:
find PATH -type d -print0 | xargs -0 run-some-command
在run-some-command
内,脚本的每个参数都将正确设置为每个目录名称,无论它包含哪些字符。
答案 2 :(得分:0)
下面的简单脚本将满足您的需求。
#!/bin/bash
function usage() {
echo "Usage: `basename $0` <dir-name>"
}
if [ "x$1" = "x" ]
then
usage
exit 0
fi
find "$1" -type 'd'