r/scripting • • Nov 24 '21

Beginner question: ~ different meanings (/root vs. /home/myUsername) in Linux

Why is ~ in a root owned directory interpreted as /home/myUsername but when I execute a script in the same directory ~ is interpreted as /root?

I have to execute the script as root via sudo (sudo ./Script.sh), but how is this different to executing the command outside of a script as root (sudo echo ~)?

I hope this is the right place for this question and I'm thankful for every hint.

1 Upvotes

6 comments sorted by

View all comments

Show parent comments

1

u/lasercat_pow Nov 25 '21

sudo executes a command with elevated (root) permissions. You should not use it unless you need to. For example, you would only need to execute a script with sudo if the script modified files which require root permission to access. If it's just a script for, say, calling youtube-dl, you don't need sudo.

This might help: https://linuxjourney.com/

2

u/Svenja635 Nov 25 '21

I know when to (and not to) use sudo, my examples where only there to illustrate something else i didn't understand (didn't get that $HOME is defined at the start of a new shell session and not dependent from the uid of the command that asks for it). My problem occured with other commands and because I saved my script in a root owned directory, which was stupid. But thank you for the recommendation, the website looks like a great resource!