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
}

相关内容