使用bash跳进每个子文件夹,然后再返回 [英] Jump into each subfolder and back again with bash

查看:157
本文介绍了使用bash跳进每个子文件夹,然后再返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写是跳跃到每个子文件夹一个bash脚本,然后跳回主文件夹(等等...)。困难是有空格的路径名。

I'm trying to write a bash script that is jumping into each subfolder and then jumps back to main folder (and so on...). The difficulty are the path names that have spaces.

 for path in "`find -type d | tr -d './'`"
 do 
    echo "Next Pathname: $path"        
    cd $path   
    echo "I'm in path $pathr"
 cd ..
 done

该错误信息是文件名或路径未找到。当我更改

The Error Message is "filename or path not found". When I change

 cd $path 

 "cd $path" 

然后我得到错误信息文件名太长。

then I get the error message "filename too long".

你能帮助我吗? - 我不知道该怎么这个字符串分隔(或写的东西更方便)

Could you help me? - I don't know how to separate this string (or write something more convenient).

推荐答案

的问题是,找到只能输出字节流的,所以你必须要小心使它输出的东西你可以在无损的方式分配。在文件路径不是唯一允许的字符是ASCII NUL,所以我们使用:

The problem is that find can only output a stream of bytes, so you have to be careful to make it output something you can split in a lossless way. The only character not allowed in a file path is ASCII NUL, so let's use that:

while IFS= read -r -d '' path
do
  ( # <-- subshell avoids having to "cd back" afterwards
    if cd "$path"
    then
      echo "I'm in $path"
    else
      echo "$path is inaccessible"
    fi
  )
done <  <(find . -type d -print0)

它能够处理各种文件名:

It handles all kinds of filenames:

$ mkdir "dir with spaces" "dir with *" $'dir with line\nfeed'

$ ls -l
total 12
drwxr-x--- 2 me me 4096 Feb  2 13:59 dir with *
drwxr-x--- 2 me me 4096 Feb  2 13:59 dir with line?feed
drwxr-x--- 2 me me 4096 Feb  2 13:59 dir with spaces
-rw-r----- 1 me me  221 Feb  2 13:59 script

$ bash script
I'm in .
I'm in ./dir with spaces
I'm in ./dir with *
I'm in ./dir with line
feed

这篇关于使用bash跳进每个子文件夹,然后再返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆