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を使用してスクリプトを実行すると、filename変数は完全なファイル名拡張子を取得できず、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

実際には、特定のファイル名を変数に割り当てません。あなたがやっていることは、変数をグローバルモードに設定することです。その後、変数をに渡すと、echoglobパターンが拡張され、ファイル名が印刷されることがわかります。ただし、変数は特定のファイル名に設定されません。

したがって、ファイル名を取得するためのより良い方法が必要です。それは次のとおりです。

#!/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
}

おすすめ記事