0

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.