linux - 列出名称中包含空格的所有目录

标签 linux shell unix sh

我想使用 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

Reference

关于linux - 列出名称中包含空格的所有目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9596565/

相关文章:

linux - 在 Linux 上安装 docker 后 Wifi 停止工作

java - Apache POI SXSSFWorkbook 在单独自动运行时无法创建工作表

Bash:按前 4 列对 csv 文件进行排序

linux - 命令行过滤日志

linux - 使用 bash shell 脚本加密文件

bash - grep 两次或一次正则表达式效率更高吗?

linux - 系统日志问题

linux - 添加一个带有字符串的数字变量

linux - 将文件复制到 vagrant 远程环境

linux - socket编程问题ipv6+udp