简体   繁体   中英

Bash script: cd No such file or directory when file exists

My bash script is written to go to each subfolder in the current directory:

for d in */; 
do
    target=${d%/}
    cd "$target"
done

When I run my bash script, I am getting a cd error for a directory that exists:

++ for d in '*/'
++ target='Zelkova serrata'
++ cd 'Zelkova serrata'
./script7.sh: line 8: cd: Zelkova serrata: No such file or directory

Yet, in terminal command line I can do cd 'Zelkova serrata' within the same directory as the script and all is fine. Is it possible the bash script has a different source directory than the one its located in?

You are looping through relative paths, try including the absolute path, for example:

#!/bin/bash

pwd=$PWD
for d in */; 
do
    target="$pwd/${d%/}"
    cd "$target"
    echo $PWD
done

The issue is that the current directory is "state" that is modified on each pass of the loop and to use the posted commands, the cwd state should not be changed by a pass.

Spawning a subshell can fix this problem of mutating state. The subshell inherits the state of its parent, but does not affect the parent.

do ( command; command ; ...; ) will spawn a new shell on each loop pass.

for d in */; 
do (
  target=${d%/}
  cd "$target"
) done

With bullet proofing

~$ find /full/path/to/dir -maxdepth 1 -type d -printo | xargs -0 -I% sh -c "cd %; echo "do some fun here""

You'll escape name splitting if there is any space there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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