我想使用 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
最佳答案
已编辑:删除了 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
关于linux - 列出名称中包含空格的所有目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9596565/