【问题标题】:syntax error in bash "if.. elif" scriptbash“if..elif”脚本中的语法错误
【发布时间】:2013-11-01 18:50:44
【问题描述】:

我正在尝试构建我的第一个脚本以在 bash 中使用“if”语句。它结合了我为创建文件的多个副本而工作的 2 个脚本,一个带有数字附加名称,另一个使用 A-Z。

我尝试了很多更改,但如果没有错误消息,我绝对无法让它工作

./cpmany.sh:第 18 行:意外标记附近的语法错误 elif' ./cpmany.sh: line 18:elif [ $alpha="A" ];那么'

这是我原来的非工作代码:

#!/bin/bash
set -x
echo "input file source"
read INPUT
echo  "Alphabetical or Numerical"
read alpha
if [ $alpha=="N" ]; then
echo "start of range"
read x
echo "end of range"
read y
    for ((i=x; i<=y; i++)); do cp "$INPUT" "$INPUT$i";
elif [ $alpha=="A" ]; then
    for i in {a..z}
    do
    echo "$i"
    cp "$INPUT" "$INPUT$i";
else
    echo "error in selection";
fi
exit 0

这是我当前的代码,在 if [ $alpha = "N" ] 中添加了“完成”和空格

#!/bin/bash
echo "input file source"
read INPUT
echo  "Alphabetical or Numerical"
read alpha


if [ $alpha = "N" ]; then
echo "start of range"
read x
echo "end of range"
read y

    for ((i=x; i<=y; i++)); do cp "$INPUT" "$INPUT$i";
done
elif [ $alpha = "A" ]; then
    for i in {a..z};
    do
    echo "$i"
    cp "$INPUT" "$INPUT$i"; done
else
    echo "error in selection";
fi
done
exit 0

【问题讨论】:

  • 您还需要在测试条件中在 = 周围放置空格,例如:[ "$alpha" = "N" ]

标签: linux bash if-statement syntax cp


【解决方案1】:

您忘记用done 关闭for 循环。

【讨论】:

  • 我在 fi 后面的行中添加了“done”,仍然出现同样的错误
  • 在“elif”之前的行添加了第二个,现在它给出了这个错误:>./cpmany.sh: line 23: syntax error near unexpected token else' &gt; ./cpmany.sh: line 23: else'跨度>
  • 这是我的代码,因为我已经用“done”#!/bin/bash set -x echo "input file source" read INPUT echo "Alphabetical or Numerical" read alpha if [ $alpha="N" ]; then echo "start of range" read x echo "end of range" read y for ((i=x; i&lt;=y; i++)); do cp "$INPUT" "$INPUT$i"; done elif [ $alpha="A" ]; then for i in {a..z} do echo "$i" cp "$INPUT" "$INPUT$i"; else echo "error in selection"; fi done exit 0 关闭了循环
  • 第二个for循环错过do前面的分号并且缺少done
  • 如果 [ $alpha="N" ];然后到 if [ $alpha = "N" ];那么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-30
  • 1970-01-01
  • 2022-01-08
  • 2012-03-24
  • 1970-01-01
相关资源
最近更新 更多