I have the following section in my bash script:
# Move to script's source directory (in case it's being called from somewhere else) cd $(dirname "${BASH_SOURCE[0]}") # Save script's source directory pwd=$(pwd) # If it's not already ~/.cfg if [ ! "$pwd" -ef ~/.cfg ]; then echo "Renaming directory" # Move up one level (since you can't rename directory while in it) cd .. # And rename it mv "$pwd" ~/.cfg fi The script is a setup script for a git repository, to be run right after cloning it. The idea is to move the entire repository to ~/.cfg. However, I get an error saying
mv: cannot move '/home/user/config' to '/home/user/.cfg': Permission denied
Permissions are set appropriately and invoking the same mv from the command line works without problems.
I'm guessing the problem is that I'm renaming a directory, while the script inside it is still running, and simply moving out of it via cd (as in the above snippet) isn't enough. Is there a way to work around that?
In the end it turned out I could do something simpler than the accepted answer below, though in the same spirit of running the removal at the very end.
I simply changed the mv command to a cp -r, then added a rm -rf "$pwd" at the very end of the script. Apparently rm's -f flag ignores the fact that the script is running. The script now works as intended.