bash 中的 Expect 腳本的檔案名稱擴展

bash 中的 Expect 腳本的檔案名稱擴展

我有以下帶有嵌入式期望腳本的 bash 腳本:

#!/bin/bash

if [ ! $# == 2 ]
  then
    echo "Usage: $0 os_base_version sn_version"
    exit
fi

if [ -e /some/file/path/$10AS_26x86_64_$2_*.bin ]
  then
    filename="/some/file/path/$10AS_26x86_64_$2_*.bin"
    echo ${filename}
else
  echo "install archive does not exist."
  exit
fi

{
  /usr/bin/expect << EOD
  set timeout 20
  spawn "${filename}"

  expect {
      "Press Enter to view the End User License Agreement" {
          send "\r"
          exp_continue
      }
      "More" {
          send " "
          exp_continue
      }
      "Do you accept the End User License Agreement?" {
          send "y\r"
      }
  }
  interact
  expect eof
EOD
}

該資料夾中有幾個格式為的文件{x}0AS_26x86_64_{x.x.x}_{rev}.bin

當我運行腳本時,我在第一次回顯時得到了正確的檔案名稱。但是當我嘗試使用將其傳遞給期望腳本時${filename},檔案名稱擴充功能消失了。

範例輸出:

# ./make.sh 2 1.2.3
/some/file/path/20AS_26x86_64_1.2.3_45678.bin
spawn /some/file/path/20AS_26x86_64_1.2.3_*.bin
couldn't execute "/some/file/path/20AS_26x86_64_1.2.3_*.bin": no such file or directory
    while executing
"spawn /some/file/path/20AS_26x86_64_1.2.3_*.bin"

正如您所看到的,$filename迴聲顯示正確,但不在預期部分內。

編輯:

只需使用 -x 運行腳本,看起來檔案名稱變數永遠不會獲得完整的檔案名稱擴展,只有 echo 可以。

# ./make.sh 2 1.2.3
+ '[' '!' 2 == 2 ']'
+ '[' -e /some/file/path/20AS_26x86_64_1.2.3_45678.bin ']'
+ filename='/some/file/path/20AS_26x86_64_1.2.3_*.bin'
+ echo /some/file/path/20AS_26x86_64_1.2.3_45678.bin
/some/file/path/20AS_26x86_64_1.2.3_45678.bin
+ exit

答案1

您實際上從未將特定的檔案名稱指派給變數。您正在做的是將變數設定為全域模式。然後,當您將變數傳遞給 時echo,glob 模式會展開,因此您會看到檔案名稱已列印。但是,該變數從未被設定為特定的檔案名稱。

因此,您需要一種更好的方法來獲取檔案名稱。就像是:

#!/bin/bash

## Make globs that don't match anything expand to a null
## string instead of the glob itself
shopt -s nullglob
## Save the list of files in an array
files=( /some/file/path/$10AS_26x86_64_$2_*.bin )
## If the array is empty
if [ -z $files ]
then
    echo "install archive does not exist."
    exit
## If at least one file was found    
else
    ## Take the first file 
    filename="${files[0]}"
    echo "$filename"
fi

{
  /usr/bin/expect << EOD
  set timeout 20
  spawn "${filename}"

  expect {
      "Press Enter to view the End User License Agreement" {
          send "\r"
          exp_continue
      }
      "More" {
          send " "
          exp_continue
      }
      "Do you accept the End User License Agreement?" {
          send "y\r"
      }
  }
  interact
  expect eof
EOD
}

相關內容