Commands referencing Homefolder via tilde run from a script appear to operate on different folders than these commans typed directly into the terminal

50 Views Asked by At

I've recently setup a new computer and wanted to collect all commands I use to setup my system in a primitive bash script. This way I thought to have an easy start with my next setup.

However, running the command

git clone --depth 1 https://github.com/doomemacs/doomemacs ~/.emacs.d

from the bash script yields Cloning into '/root/.emacs.d', while running it from the terminal directly actually clones into ~/.emacs.d (which I as an amateur understand to lie directly in my home folder). Before that command there is only a simple pacman -S instruction in my script. I also ran the bash script in different places (home folder and subfolders), but this has not changed the outcome.

Can someone please explain to me why the command appears to act differently from my bash script? Is ~ when run from a script with sudo expanded into some sort of "Home directory of root" and if so, how may I stop this and reliably refer to the home directory of the current user that is logged in when employing the script?

As @Jetchisel pointed out, it is probably important that I run the bash script with sudo, which is necessary since it contains a pacman -S instruction. If, however, I run an individual command with sudo, ~ will be expanded to the desired homefolder. So running sudo rm -rf ~/testfoldercreatedfordeletion in fact deletes the desired folder in my personal home directory. If I include the same line without sudo in the bash script, and run the bash script with sudo it does not.

0

There are 0 best solutions below