
我正在 Raspberry Pi OS(基於 Debian 12 Bookworm)上編寫 bash 腳本。該腳本嘗試做類似的事情
ssh "$args" "$user"@"$ip" 'command'
據我所知,這是標準做法。然而我發現 when$args
包含多個參數,例如
-v -i /path/to/keyfile -o StrictHostKeyChecking=yes
然後執行
ssh "$args" "$user"@"$ip" 'echo "Success in logging into $HOSTNAME"'
ssh 傳回以下內容,退出狀態為255
:
unknown option --
usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]
[-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
[-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]
[-i identity_file] [-J [user@]host[:port]] [-L address]
[-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]
[-Q query_option] [-R address] [-S ctl_path] [-W host:port]
[-w local_tun[:remote_tun]] destination [command [argument ...]]
$args
但是,僅使用 的內容而不是 using 執行相同的命令$args
會成功並以狀態退出0
:
ssh -v -i /path/to/keyfile -o StrictHostKeyChecking=yes "$user"@"$ip" 'echo "Success in logging into $HOSTNAME"'
重申一下,$args
當只有一個參數時, using 效果非常好,例如
-o StrictHostKeyChecking=yes
這裡發生了什麼事?我可以做什麼來防止這種情況發生?從unknown option --
看來,有些東西正在解析$args
並從中剝離一些東西,因為它只在有兩個或多個參數時才會抱怨這一點(兩次出現-
in $args
)?
答案1
(我可能應該將其作為重複項關閉,但無論如何讓我們嘗試解釋特定情況。)
引用的擴展"$args"
產生一參數,所以實際上你正在運行ssh "-v -i /path/to/keyfile -o StrictHostKeyChecking=yes" ...
。其中的空格和破折號被視為選項字符,類似於堆疊選項在更有用的情況下的工作方式,例如-abc
.破折號不是有效選項,因此您會收到投訴。
如果ssh "$args"
似乎適用於args='-o StrictHostKeyChecking=yes'
,那可能是因為解析器 for-o
忽略空格(類似於ssh_config
忽略空格 in 的方式)。嘗試相同的操作args='-i /path/to/keyfile'
,您可能會收到檔案未找到錯誤,因為您剛剛在檔案名稱中包含了一個前導空格。 (args='-i/path/to/keyfile'
當然,沒有空間也可以。)
看: