Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 在远程服务器上执行命令的bash脚本将输出打印两次_Linux_Bash_Shell - Fatal编程技术网

Linux 在远程服务器上执行命令的bash脚本将输出打印两次

Linux 在远程服务器上执行命令的bash脚本将输出打印两次,linux,bash,shell,Linux,Bash,Shell,我的输入文件如下所示 文件名:/etc/hosts 10.142.75.6 m1 10.142.75.7 m2 10.142.75.8 m3 下面的脚本在/etc/hosts中查找主机名,并应打印命令“nproc”的输出,但它将打印两次输出,一次用于ip及其相应的主机名 for hosts in $(cat /etc/hosts) ; do ssh $hosts "uname -a" done 您可以使用cut仅读取文件的第一列: for hosts in $(cut -d

我的输入文件如下所示

文件名:/etc/hosts

10.142.75.6 m1 

10.142.75.7 m2 

10.142.75.8 m3
下面的脚本在/etc/hosts中查找主机名,并应打印命令“nproc”的输出,但它将打印两次输出,一次用于ip及其相应的主机名

for hosts in $(cat /etc/hosts) ;
do
     ssh $hosts "uname -a"
done

您可以使用
cut
仅读取文件的第一列:

for hosts in $(cut -d' ' -f1 < /etc/hosts);
do
    echo "jps for $hosts"
    ssh $hosts "uname -a"
done
主机的
单位为美元(cut-d'-f1
目前,您正在将文件中的每个单词解析为主机名——因此,您首先通过其IP连接到每个主机,然后再通过其名称连接到第二个主机


最好使用最佳做法来读取文件:

# read first two columns from FD 3 (see last line!) into variables "ip" and "name"
while read -r ip name _ <&3; do

 # Skip blank lines, or ones that start with "#"s
 [[ -z $ip || $ip = "#"* ]] && continue

 # Log the hostname if we read one, or the IP otherwise
 echo "jps for ${name:-$ip}"

 # Regardless, connect using the IP; don't allow ssh to consume stdin
 ssh "$ip" "uname -a" </dev/null

# with input to FD 3 from /etc/hosts
done 3</etc/hosts
#将fd3的前两列(见最后一行!)读入变量“ip”和“name”

虽然read-r ip name ubash将
$(cat/etc/hosts)
替换为
10.142.75.6 m1 10.142.75.7 m2 10.142.75.8 m3
…但一般来说,您不应该对x in$(cat…
使用
。假设您有一行/etc/hosts,上面写着“总是通知”someone@example.com在更改此文件之前*
——您当前的代码将用文件名列表替换这些文件,并尝试通过ssh连接到这些文件。顺便说一句,通过使用
bash-x yourscript
运行脚本来记录您的脚本所做的事情,可能已经清楚地说明了当前的问题。我不确定是否有理由对此进行否决——我显然认为这并不理想,但是它在任何方面都完全错误的唯一地方是,
$hosts
扩展中缺少引号。它也不会跳过hosts文件中的注释,但这也是相当小的。我认为不应该鼓励不好的做法,因为它可能适用于这一特定文件。