在 ssh 命令內分配的變數未傳回正確的值

在 ssh 命令內分配的變數未傳回正確的值

ssh我正在我的腳本部分執行以下命令。該命令旨在減少ls選項中的檔案大小並將其儲存到變數中。然後列印變數:

echo "Enter srouce file";
read src_file;
src_size =`ls -latr $src_file | awk  '{ print $5 }' `;
echo "The source file size is $src_size ";

當它在命令列上執行時,效果很好。

當我透過以下方式在腳本中嘗試相同的命令時ssh

ssh user@server "echo "enterfile";read src_file;echo "enter path ";read path;cd $path;src_size=`ls -latr $src_file | awk  '{ print $5 }' ` ; echo The source file size is $src_size;"

這失敗了。它存儲一些本地臨時值並傳回相同的檔案大小而不是正確的檔案大小。

答案1

使用腳本可以避免因引用問題而弄亂命令。

它更乾淨、更易於管理並且看起來更好:)!

例如,只需這樣做:

echo "Enter source file"
read src_file
ssh user@server 'bash -s' < /path/to/local_script.sh "$src_file"

內容local_script.sh

#!/bin/bash
src_file="$1"
src_size =`ls -latr $src_file | awk  '{ print $5 }'`
echo "The source file size is $src_size "

不要忘記添加路徑local_script.sh:)

答案2

如果不進行一些轉義,就無法將雙引號嵌套在其他雙引號中 - 並且通過將反引號放入雙引號中,它們將在本地計算機而不是遠程計算機上進行評估。

類似這樣的事情應該可以完成您想要完成的任務:

ssh user@server 'echo "Enter file: "; read src_file; echo "Enter path: "; read path; cd $path; src_size=`ls -latr $src_file | awk  "{ print \$5 }"`; echo "The source file size is $src_size;"'

請注意,我需要將 更改為'{ print $5 }'"{ print \$5 }"轉義 ,$因為它現在位於雙引號而不是單引號內,並且我不希望$5shell 解釋 。

相關內容