简体   繁体   English

Shell脚本无法CD进入包含空格的目录

[英]shell script unable to cd into a directory that contains spaces

I have a shell script that loops into each directory and finding a file. 我有一个shell脚本,该脚本循环进入每个目录并找到一个文件。 The problem I have is shell script is unable into cd to a directory that contains space. 我的问题是shell脚本无法进入cd到包含空间的目录。 Here is example script. 这是示例脚本。

First method: 第一种方法:

for dir in "$(find /usr/tom/public/junk -maxdepth 3 -type f -name testfile)"; do
        cd "$(dirname "$dir")"
        printf "%-54s" $(basename $PWD)
       done 

second method: 第二种方法:

find "/usr/tom/public/junk" -maxdepth 3 -type f -name testfile -print |
  while IFS= read -r dir
  do
    cd "$(dirname "$dir")"
    printf "%-54s" $(basename $PWD)
    done 

Error : No such file or directory ( because some directories contains spaces) 错误:没有这样的文件或目录(因为某些目录包含空格)

my requirement is -> When a "test" file is found in a directory then it has to delete that directory. 我的要求是->当在目录中找到“测试”文件时,它必须删除该目录。

I am running this script on ubuntu.And the weird part is, this piece of code working in my Mac but not on ubuntu server. 我正在ubuntu上运行此脚本。奇怪的是,这段代码可以在Mac上运行,但不能在ubuntu服务器上运行。 I have no idea why it is not working on ubuntu. 我不知道为什么它不能在ubuntu上工作。 Please help me. 请帮我。

The problem with spaces in directorynames can be circumventing by using read to process the output from find . 通过使用read处理find的输出,可以避免目录名中存在空格的问题。 There is an very thorough explanation for that in this answer . 这个答案有一个非常彻底的解释。 For your situation, something like this would work: 对于您的情况,这样的事情会起作用:

find /usr/tom/public/junk 3 -type f -name testfile | while read dir; do
    cd "$(dirname $dir)"
done

Use double quotes to the directory names. 在目录名称中使用双引号。

mahendra@test-Ubuntu:~$ cd /test
mahendra@test-Ubuntu:-Ubuntu:/opt$ cd "new test"

As the folder you want to connect has spaces in the name, you must surround the name with quotes in order for the Shell to read it correctly (as one name). 由于要连接的文件夹的名称中包含空格,因此必须在名称两端加上引号,以使Shell正确读取它(作为一个名称)。

now you need to check how you can pass "" to directories in the shell script. 现在,您需要检查如何将“”传递到shell脚本中的目录。

another way is you can use the backslash 另一种方法是您可以使用反斜杠

cd test\ Text\ 2/

the backslash followed by a space explicitly denotes a space. 反斜杠后跟一个空格,明确表示一个空格。

suggestion: do not create a directory with space in Linux. 建议:不要在Linux中创建带有空间的目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM