条件是/否

条件是/否

我正在运行以下代码作为脚本的一部分(#!/bin/bash)。

read -p "Do you want to make use of Thorpe volume attenuation in the watercolumn [Y/N]:" Thorpe
read -p "Do you want to include *.ati file? [Y/N]:" ati
Thorpe_att=T
ati_file=*
if [$Thorpe = Y]; then
   if [$ati = Y]; then
      echo "Usage of Thopre volume attenuation volume and *.ati file is accepted"
      sed -i "4s/''/'$interp$surf$attenuation$Thorpe_att$ati_file'/" $Mod_Filename
   else
      echo "Only usage of Thopre volume attenuation volume is accepted"
      sed -i "4s/''/'$interp$surf$attenuation$Thorpe_att'/" $Mod_Filename
   fi
else 
   if [$ati = Y]; then
      echo "Only usage of *.ati file is accepted"
      sed -i "4s/''/'$interp$surf$attenuation$ati_file'/" $Mod_Filename
   else
      echo "Neither usage of Thopre volume attenuation volume nor *.ati file is accepted"
      sed -i "4s/''/'$interp$surf$attenuation'/" $Mod_Filename
   fi
fi

运行后出现此错误:

./mod.sh: line 50: [N: command not found
./mod.sh: line 59: [N: command not found

随后,它在终端上打印出一行 :echo “Neither usage...”。有人能解决这个问题吗?提前致谢。

答案1

您的测试命令中缺少空格。此部分:

if [$Thorpe = Y]; then
   if [$ati = Y]; then
      ...

应该

if [ $Thorpe = Y ]; then
   if [ $ati = Y ]; then
      ...

如果没有空格,shell 会将 的值扩展$ThorpeN并尝试运行[N,它将其视为命令。它不认为这是一个有效的命令,并输出您看到的错误。

就我个人而言,我更喜欢使用[[ $Thorpe = Y ]]Bash 内置函数,而不是test,( [ $Thorpe = Y ]),它可以更好地处理未加引号的字符串,并且更明显地使用 && 和 || 运算符。

答案2

错误是缺少空格。[ ]构造总是需要空格,所以[foo]是错误的但是[ foo ]正确的。因此,对于你的情况,请更改

if [$Thorpe = Y]; then

if [ $Thorpe = Y ]; then

更笼统地说,你为什么要让用户的生活如此艰难?停止程序的执行并要求用户费力地手动输入是非常糟糕的设计。尤其是在要求输入一个可以使用制表符补全轻松给出且很可能输入错误的文件名时。

不要强迫用户回答问题,而是编写脚本以便它可以处理命令行选项,或者至少使传递的任何参数都自动假定为您要求的任何值。

相关内容