Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cd into directory in while loop doesn't work

Tags:

bash

I've the following script:

#!/bin/bash

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

Problem is that each cd says "[path]: No such file or directory", why? Folder exists because I list it ...

like image 899
Arnaud F. Avatar asked May 04 '12 09:05

Arnaud F.


People also ask

Why cd command is not working in shell script?

Trying to use cd inside the shell script does not work because the shell script runs in the subshell and once the script is over it returns to the parent shell, which is why the current directory does not change.

How do you loop a directory in Linux?

We use a standard wildcard glob pattern '*' which matches all files. By adding a '/' afterward, we'll match only directories. Then, we assign each directory to the value of a variable dir. In our simple example, we then execute the echo command between do and done to simply output the value of the variable dir.


1 Answers

I see two problems in your code:

  1. You do not test for directories.
  2. Once you cd in the dir, you stay there.

Please try this:

#!/bin/bash

ls -1 | while read d
do 
    test -d "$d" || continue
    echo $d
    (cd $d ; echo "In ${PWD}")
done
like image 87
Andreas Florath Avatar answered Nov 06 '22 21:11

Andreas Florath