Jump into each subfolder and back again with bash

你说的曾经没有我的故事 提交于 2019-12-12 03:26:02

问题


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 

to

 "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).


回答1:


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


来源:https://stackoverflow.com/questions/28285639/jump-into-each-subfolder-and-back-again-with-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!