Bash

bash 變數不保留命令結果

  • November 17, 2017

問題:

將命令結果儲存在變數portcheck中未按預期工作。我的腳本包含此方法

#!/bin/bash
...

status() {
   portcheck=$(nc -z -v -w5 localhost 8443)
   echo "*${portcheck}*"
   if [[ $portcheck == *refused* ]]; then
         echo "Application is stopped"
   elif [[ $portcheck == *succeeded* ]]; then
         echo "Application is started"
   else
         echo "state unknown"
   fi
}

當我執行 myscript 時,我得到以下結果:

> $  ./myscript status 
> Connection to localhost 8443 port [tcp/*] succeeded!
> ** 
> state unknown

但我想要的是命令的結果儲存在變數portcheck中,輸出應該看起來像

> $  ./myscript status 
> Connection to localhost 8443 port [tcp/*] succeeded!
> *Connection to localhost 8443 port [tcp/*] succeeded!* 
> Application is started

我根據https://stackoverflow.com/questions/4651437/how-to-set-a-variable-to-the-output-from-a-command-in-bash 等嘗試了幾種變體, 例如

portcheck=`nc -z -v -w5 localhost 8443`

代替

portcheck=$(nc -z -v -w5 localhost 8443)

但它沒有用。我究竟做錯了什麼?

背景:

命令

nc -z -v -w5 localhost 8443

檢查埠是否可連接。它返回

Connection to localhost 8443 port [tcp/*] succeeded!

如果埠是“開放的”並且

nc: connect to localhost port 8443 (tcp) failed: Connection refused

如果埠“關閉”。

如果我只是在 bash 中執行普通命令,這很好用。

nc呼叫基本上列印到 stderr,您需要將輸出發送到 stdout,如下所示:

portcheck=$(nc -z -v -w5 localhost 8443 2>&1)
echo "*${portcheck}*"

這將是輸出,在這種情況下:

*Connection to localhost 8443 port [tcp/*] succeeded!*

引用自:https://unix.stackexchange.com/questions/405217