簡體   English   中英

使用其他腳本作為變量在 bash 腳本中堆疊 SSH 命令 arguments 時出錯

[英]Error when stacking SSH command arguments within a bash script using other scripts as variables

我有一個名為addresses.csv的csv文件,看起來像這樣,

node-1,xx.xxx.xx.xx,us-central-a
....
node-9,xxx.xx.xxx.xx,us-east1-a

我在下面有一個名為 0run.sh 的腳本,

#!/bin/bash
username='user'
persist="bash /home/${username}/Documents/scripts/disk/persistentDisk.sh"
first="bash /home/${username}/Documents/scripts/disk/firstAttach.sh"

while IFS=, read -r int ip <&3; do
  if [ "$int" == "node-1" ]; then
--->ssh -i ~/.ssh/key -o StrictHostKeyChecking=no -l ${username} ${ip} "${persist}; ${first}"<---
  else
    ssh -i ~/.ssh/key -o StrictHostKeyChecking=no -l ${username} ${ip} "${first}"
  fi
done 3<addresses.csv

錯誤發生在我繪制箭頭的代碼部分。

當它在node-1上運行時,而不是運行..persistentDisk.sh后跟..firstAttach.sh ,它只運行..persistentDisk.sh並在運行..persistentDisk之前給我以下錯誤。

bash: /home/user/Documents/scripts/disk/firstAttach.sh: No such file or directory

腳本的 rest 運行完全正常。 唯一的錯誤發生在這一部分,它錯過了第二個腳本。

當我像這樣運行命令時,它運行良好。

ssh -i ~/.ssh/key -o StrictHostKeyChecking=no -l ${username} ${ext} "${first}"

當我這樣運行它時,它也運行良好。

ssh -i ~/.ssh/key -o StrictHostKeyChecking=no -l user xxx.xx.xxx.xx "bash /home/${username}/Documents/scripts/disk/persistentDisk.sh; bash /home/${username}/Documents/scripts/disk/firstAttach.sh"

當我像在;之前使用\一樣運行命令時像這樣逃避它,

ssh -i ~/.ssh/key -o StrictHostKeyChecking=no -l ${username} ${ext} "${persist}\; ${first}"

我收到以下錯誤,並且兩個腳本都沒有在代碼的node-1部分中運行,但是代碼的 else 循環的 rest 運行良好。

bash: /home/user/Documents/scripts/disk/persistentDisk.sh;: No such file or directory

為什么我不能使用變量在 ssh 的 if 語句中堆疊 2 個命令?

如果我清楚地理解:您真正的問題在於讓STDIN自由以在目標主機中進行交互!

關於read和重定向

嘗試使用:

#!/bin/bash
username='user'
persist="bash /home/${username}/Documents/scripts/disk/persistentDisk.sh"
first="bash /home/${username}/Documents/scripts/disk/firstAttach.sh"

while IFS=, read -r -u $list int ip foo; do
  if [ "$int" == "node-1" ]; then
       echo CMD... $ip, $persist
  else
       [ "$ip" ] && echo CMD... $ip, $first
  fi
done {list}<addresses.csv

經過測試,這 èroduce:

CMD... xx.xxx.xx.xx, bash /home/user/Documents/scripts/disk/persistentDisk.sh
CMD... xxx.xx.xxx.xx, bash /home/user/Documents/scripts/disk/firstAttach.sh
  • -u讀取標志,告訴使用文件描述符${list}而不是STDIN
  • foo是一些無用的變量,用於防止將行的 rest 存儲在$ipxx.xxx.xx.xx,us-central-a在這種情況下)
  • {list}</path/to/filename通過查找任何空閑文件描述符來創建一個新變量。

關於ssh (和重定向)

你可以使用:

#!/bin/bash
username='user'
persist="/home/${username}/Documents/scripts/disk/persistentDisk.sh"
first="/home/${username}/Documents/scripts/disk/firstAttach.sh"

while IFS=, read -r -u $list int ip foo; do
  [ "$int" = "node-1" ] && cmd=persist || cmd=first
  [ "$ip" ] && ssh -i ~/.ssh/key -t -o StrictHostKeyChecking=no \
                   -l ${username} ${ext} /bin/bash "${!cmd}"
  done {list}<addresses.csv

通過使用此語法,您將保持STDIN自由,以便在目標主機上運行腳本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM