2

I'm creating a login message for my computer inside of /etc/bashrc and would like to greet them to the computer with the computer's name showing.

Here's my code:

# (system stuff here)
echo "Welcome, $(whoami)."

When I use login on any user, it gives me what I'd expect: Welcome, avgjoe for example.

However, I'd like to make it output Welcome, avgjoe, to Tower of Nix - my computer's name has been set (through System Preferences) to "Tower of Nix" already.

So, without hard-coding it in there (i.e. echo "Welcome, $(whoami), to Tower of Nix."), how can I get the name of my computer?

I've already tried hostname, but that outputs 192.168.2.13.

Turns out, scutil --get ComputerName does exactly what I want (outputs Tower of Nix), but when I looked at the man page for scutil, it stated:

HISTORY

The scutil command appeared in the Mac OS X Public Beta.

So it probably won't work on all operating systems such as Linux, *BSD, etc.

My question: How can I get the name of the computer on any (or nearly any) derivative of UNIX?

Nebula
  • 125
  • Your behaviour of hostname sounds more like hostname -i to me. For completeness' sake, can you try hostname -a (show alias name) and hostname -s (show short host name)? – Ulrich Schwarz Jul 31 '15 at 16:13
  • 1
    Can you do an alias | grep hostname on your system? Because AFAIK hostname is pretty universal across OSes (*nix, NetWare, Windows, ...) – Fabby Jul 31 '15 at 16:24
  • Updated to obviously explain the output of hostname: 192.168.2.13 – Nebula Jul 31 '15 at 16:30
  • 2
    The Mac is the only Unix-like system I know of that lets you store and retrieve a name totally distinct from the computer's IP hostname. It's probably best to special-case it, maybe $(scutil --get ComputerName 2>/dev/null || hostname) . – Mark Plotnick Jul 31 '15 at 17:37

3 Answers3

4

Many but not all Unix like system's uname have the n option

    uname -n
fd0
  • 1,449
2

Mac OS X is one of the few Unix-like systems that lets you store and retrieve a name totally distinct from the computer's IP hostname. It's probably best to special-case the call to scutil; if that fails, fall back to the more standard hostname:

echo "Welcome, $(whoami), to $(scutil --get ComputerName 2>/dev/null || hostname)."
Mark Plotnick
  • 25,413
  • 3
  • 64
  • 82
  • The USER environment variable is set by the login process, so it's safe to use $USER with any shell. – fd0 Jul 31 '15 at 18:46
0

Hostnames on GNU/Linux are simply inside a file. For example, I can edit my hostname on Slackware by changing a single line in /etc/HOSTNAME.

My suggestion would just be to concatenate that file into your command in bashrc. If your system does not have a hostname file in /etc you can simply create one. Also, you can use $USER instead of whoami because the variable USER is populated with the name of whoever is logged in.

This is what the command can look like:

echo "Welcome, $USER, to `cat /etc/HOSTNAME`"
Peschke
  • 4,148