bash 内の expect スクリプトのファイル名の拡張

bash 内の expect スクリプトのファイル名の拡張

次のような 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

スクリプトを実行すると、最初のエコーで正しいファイル名が取得されます。しかし、 を使用してこれを expect スクリプトに渡そうとすると${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"

ご覧のとおり、$filenameecho では正しく表示されますが、expect 部分では正しく表示されません。

編集:

-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

実際に変数に特定のファイル名を割り当てることはありません。変数を glob パターンに設定するだけです。次に、変数を に渡すと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
}

関連情報