bash 如何使用shell脚本知道代码正在运行的当前服务器名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33564888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:52:53  来源:igfitidea点击:

How to know current server name where the code is running using shell script?

bashshellunixhostname

提问by tanmayghosh2507

I have a shell script code, which can run on any one of the 6 servers and one file gets updated. But I need to maintain a common file to get the most updated changes in the file and apply certain logic on the latest file. So, I want to know the current server name where it is running at that particular moment?

我有一个 shell 脚本代码,它可以在 6 个服务器中的任何一个上运行,并且一个文件得到更新。但是我需要维护一个通用文件以获取文件中最新的更改并在最新文件上应用某些逻辑。所以,我想知道它在那个特定时刻运行的当前服务器名称?

Here is my code, I have fixed a abc.com server my common server where I am saving the file and next time I am retrieving the file from it. But I also need the current server name, as some operations need to be done based on current server. So, I just want to add one line of code which gives me back the current server where it is running.

这是我的代码,我已将 abc.com 服务器固定在我的公共服务器上,我将在其中保存文件,下次我从中检索文件时。但是我还需要当前服务器名称,因为一些操作需要基于当前服务器来完成。所以,我只想添加一行代码,让我返回运行它的当前服务器。

#!/bin/bash
# This code copies the file with latest changes to a common location.

server_name=abc.com

# backlog.txt is my file name
echo - removing the old files , if any
rm $server_name:/home/backlog.txt

echo "$server_name to copy the file"

scp /location/backlog.txt $server_name:/home/

echo "Copy complete."

exit 0

And this:

和这个:

#!/bin/bash
# This code copies back the common file from common server location "abc" and then make the changes into it. As I always need to work on the latest file.

server_name=abc.com

echo - removing the old files , if any
rm /location/backlog.txt

echo "Copying the files from $server_name to local server..."

scp $server_name:/home/backlog.txt /location/

echo "Copy Complete"

exit 0

回答by Jakuje

hostnameutility usually does what you need.

hostname实用程序通常可以满足您的需求。