masterq
masterq

Reputation: 203

Remove part of $(hostname)') in bash script?

I am running a script to automatically update a field inside a database with the servers hostname

updatevar="UPDATE email_lists SET owneremail = REPLACE(owneremail, 'replacethis321', '$(hostname)');"

However, the hostname is "xyz.com"; how would I make it only be "xyz"? The script needs to remove the ".com" part. This is used on multiple servers so I can't just set it to xyz.

Upvotes: 0

Views: 2114

Answers (2)

Jason Dowd
Jason Dowd

Reputation: 21

Alternatively you can pipe to awk instead of getting the hostname in a separate variable.

$(hostname | awk -F "." '{print $1}')

Upvotes: 2

Charles Duffy
Charles Duffy

Reputation: 295510

Instead of using $(hostname) directly, assign it to a shell variable so you can use PE expressions at expansion time:

hostname=$(hostname)
updatevar="... ${hostname%%.*} ..."

The use of %%.* trims everything after the first dot. You could instead use ${hostname%.com} if you only wanted to remove the suffix .com (but leave .org, .net, etc alone).

Alternately, instead of $(hostname), use $(hostname -s) if your operating system supports it; this is the "short" form, truncated at the first dot.


That said -- using string substitutions to form SQL expressions is bad form (and since bash doesn't typically give you a way to use bind variables in running SQL, it's usually necessary/appropriate to use a different language if you genuinely want to do the job right). Even the Wooledge bash guide explicitly calls out database interaction as a limitation.

Upvotes: 2

Related Questions