bash

Use of CD in Bash For Loop - only getting relative path


I have a small script that I use to organizes files in directories, and now I am attempting to run it on a folder or directories. MasterDir/dir1, MasterDir/dir2, etc.

Running the following code on MasterDir results in an error as the $dir is only a relative path, but I can't figure out how to get the full path of $dir in this case

for dir in */; do
    echo $dir
    cd $dir
    cwd="$PWD"
    mkdir -p "VSI"
    mv -v *.vsi "$cwd/VSI"
    mv -v _*_ "$cwd/VSI"
done

Solution

  • I'd suggest using parentheses to run the loop body in a subshell:

    for dir in */; do
        (
            echo "$dir"
            cd "$dir"
            cwd=$PWD
            mkdir -p "VSI"
            mv -v *.vsi "$cwd/VSI"
            mv -v _*_ "$cwd/VSI"
        )
    done
    

    Since that's running in a subshell, the cd command won't affect the parent shell executing the script.