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 ...
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.
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.
I see two problems in your code:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With