I have to get the hostname for a network device out of its config file. The file looks like:
...
hostname=T14Z18
ipaddress=192.168.0.1
...
How does one do that? I am ssh'ing into the machine.
I have to get the hostname for a network device out of its config file. The file looks like:
...
hostname=T14Z18
ipaddress=192.168.0.1
...
How does one do that? I am ssh'ing into the machine.
Use grep and cut like that:
$ grep '^hostname=' configfile | cut -d= -f2
T14Z18
You can also combine the above with ssh command in Bash:
$ ssh "$(grep '^hostname=' configfile | cut -d= -f2)"
Everything between $( and ) will be replaced by the output of the command inside the parenthesis so it would be the same as if you typed ssh T14Z18 manually.
This feature is called command
substitution
in Bash.
Also notice that OpenSSH that you probably use has its own config
stored in ~/.ssh/config that you can use to create aliases. For
example, the following entry creates an alias called rpi:
Host rpi
User pi
Hostname 192.168.1.161
You can now just do ssh rpi and user and hostname will be found
automatically by OpenSSH client. You can of course use a hostname such as T14Z18 is in your example instead of IP address if you have DNS server in your network.
ssh "$(grep '^hostname=' configfile | cut -d= -f2)" -- that way if you don't get exactly one word out, the error message will make sense (rather than additional words being treated as parts of a command to send to the remote machine, or 0-words passing the first subsequent argument to ssh as the hostname).With simple awk command:
awk -F'=' '$1 == "hostname"{ print $2; exit }' configfile
grep | cut, and also has the effect of head -n 1, preventing multiple matches.With gnu-grep if -P pcre regex switch is implemented :
grep -oP 'hostname=\K.*' configfile
__
^
|
restart the match trick
grep, when compiled with optional PCRE support" to be a little more up-front about the portability constraints.grep with such support links in the 3rd-party library in libpcre at compile time, so I believe describing it as "PCRE" is entirely appropriate here.man grep is not that clear, it says perl regex and PCRE, that is not the samegrep -P is implemented by pcresearch.c in the codebase. See git.savannah.gnu.org/cgit/grep.git/tree/src/pcresearch.c for the source. It's absolutely PCRE.