使用"读取时"时,如何正确格式化传递给远程服务器的"if"语句?



Ubuntu 18
Bash 4.4.0

我想传递一个 if 语句以查看目录是否存在。如果是这样,我想要一些命令,然后是一个文件。我已经通读了类似的帖子,但shellcheck抱怨我的格式。

脚本:

#!/bin/bash
testing="yes"
scriptDir="/root/.work"
wDir="${scriptDir}/.nginx-fix"
if [ "$testing" = "no" ]; then
hostfile="${scriptDir}/.zzz-hostnames"
else
hostfile="${scriptDir}/.zzz-hostnames-tester"
fi
cd "$wDir"
while read fqdn; do
{ clear; echo ""; echo ""; echo "$hostname"; echo ""; }
< /dev/null if ssh -p 34499 root@"${fqdn}" '[ -d /etc/nginx ]'; then
< /dev/null ssh -p 34499 root@"${fqdn}" 'mv /etc/nginx/nginx.conf /etc/nginx/.nginx-sept-30'
< /dev/null scp -P 34499 nginx.conf root@"${fqdn}":/etc/nginx
< /dev/null ssh -p 34499 root@"${fqdn}" 'sed -i "/honeypot/d" /etc/nginx/conf.d/*.conf'
< /dev/null ssh -p 34499 root@"${fqdn}" 'nginx -t'
else
exit 1;
fi
done<"${hostfile}"

壳牌投诉:

root@me ~/.work/.nginx-fix # shellcheck .nginx-fixer.sh
In .nginx-fixer.sh line 13:
while read fqdn; do
^-- SC1073: Couldn't parse this while loop.
^-- SC1061: Couldn't find 'done' for this 'do'.

In .nginx-fixer.sh line 15:
< /dev/null if ssh -p 33899 root@"${fqdn}" '[ -d /etc/nginx ]'; then
  ^-- SC1062: Expected 'done' matching previously mentioned 'do'.
      ^-- SC1072: Expected "#". Fix any mentioned problems and try again.

我很感激你的想法。

您可以将脚本重构为更清晰的版本并删除所有</dev/null

while read -r fqdn; do {
{ clear; echo ""; echo ""; echo "$hostname"; echo ""; }
if ssh -p 34499 root@"${fqdn}" '[ -d /etc/nginx ]'; then
ssh -p 34499 root@"${fqdn}" 'mv /etc/nginx/nginx.conf /etc/nginx/.nginx-sept-30'
scp -P 34499 nginx.conf root@"${fqdn}":/etc/nginx
ssh -p 34499 root@"${fqdn}" 'sed -i "/honeypot/d" /etc/nginx/conf.d/*.conf'
ssh -p 34499 root@"${fqdn}" 'nginx -t'
else
exit 1;
fi
} </dev/null; done < "${hostfile}"

肉眼几乎看不见,我把所有的命令都放在里面do ... done里面{ .. } </dev/null.这样,任何命令都不会从${hostfile}读取,也不会弄乱while read

另一种选择是使用专用的文件描述符并传递其编号以读取:

while read -r -u 10 fqdn; do
{ clear; echo ""; echo ""; echo "$hostname"; echo ""; }
if ssh -p 34499 root@"${fqdn}" '[ -d /etc/nginx ]'; then
ssh -p 34499 root@"${fqdn}" 'mv /etc/nginx/nginx.conf /etc/nginx/.nginx-sept-30'
scp -P 34499 nginx.conf root@"${fqdn}":/etc/nginx
ssh -p 34499 root@"${fqdn}" 'sed -i "/honeypot/d" /etc/nginx/conf.d/*.conf'
ssh -p 34499 root@"${fqdn}" 'nginx -t'
else
exit 1;
fi
done 10<"${hostfile}"

通过"bash -n"运行脚本将指示"真正的"错误:

bash -n x.sh
x.sh: line 15: syntax error near unexpected token `then'
x.sh: line 15: `   < /dev/null if ssh -p 34499 root@"${fqdn}" '[ -d /etc/nginx ]' ; then'

您不能在"if"语句之前放置重定向。将重定向移动到"ssh"(if的条件部分(命令,例如:

# USE:
if ssh < /dev/null -p 34499 root@"${fqdn}" '[ -d /etc/nginx ]' ; then'
# AND NOT:
< /dev/null if ssh -p 34499 root@"${fqdn}" '[ -d /etc/nginx ]' ; then'

相关内容

  • 没有找到相关文章

最新更新