Cd to directory during loop not working

I have the following script:

#!/bin/bash

ls -1 | while read d
do 
    [[ -f "$d" ]] && continue
    echo $d
    cd $d
done

The problem is that each cd says "[path]: there is no such file or directory", why? The folder exists because I list it ...

+3
source share
4 answers

I see two problems in your code:

  • You do not check directories.
  • Once you are cdin the directory, you will remain there.

Please try the following:

#!/bin/bash

ls -1 | while read d
do 
    test -d "$d" || continue
    echo $d
    (cd $d ; echo "In ${PWD}")
done
+5
source

You should not use ls.

#!/bin/bash

for d in *
do 
    [[ ! -d "$d" ]] && continue
    echo "$d"
    cd "$d"
    # do something
    cd "$OLDPWD"
done
+2
source

, script. , cd , cd.

dir=`pwd`
ls -1 | while read d
do 
    [[ -f "$d" ]] && continue
    cd "$dir"
    echo $d
    cd $d
    #....
done
0

, . - ?

:

#!/bin/bash                                                                                                                                                                                                                            
CWD="$(pwd)" #save starting directory
ls -1 | while read d
do
    [[ ! -d "$d" ]] && continue
    cd "$d"
    echo "Changed to directory" $d
    #Now you can do someting in the sub-directory
    cd "$CWD" #Change back to old directory
done
0

All Articles