从 BASH 脚本返回“意外的文件结尾”

hip*_*ngs 0 bash

不知道为什么我得到这个。我意识到这一定是一个常见问题,但无法弄清楚。

#!/bin/bash
 #Checks word count of each text file directory and deletes if less than certain   amount of words
 #Lastly, displays number of files delter

 count = 0 #Set counter to 0
 limit = 2000

 for file in *.txt
 do
     words = wc -w > $file
     if words < $limit
         rm $file
         count = $count + 1
     end
 end

 print "Number of files deleted: $count" 
Run Code Online (Sandbox Code Playgroud)

ter*_*don 5

恐怕你的脚本充满了语法错误。您看到的具体错误是因为您没有for正确关闭循环,但还有很多很多:

  1. =给变量赋值时不能有空格(算术表达式除外);
  2. 为了将命令的输出保存在变量中,您必须使用命令替换var=`command`或者var=$(command);
  3. 引用变量的值时,必须使用$var, not var,一般情况下,需要用引号 ( "$var");
  4. 在做一个算术比较,你需要使用-lt的的[命令,不<,除非你使用双括号;
  5. command > file格式将被file命令的输出覆盖。您可能打算使用wc < "$file"而不是wc > $file
  6. var=$var+1除非该变量之前已声明为整数,否则您无法向变量添加值,您需要((var=var+1)),var=$((var+1))declare -i var; var=var+1。要加 1,您还可以使用((var++));
  7. 你的if语法是错误的。正确的格式是if condition; then do something; fi
  8. 这同样适用于for循环,正确的语法是for loop-specification; do something; done;
  9. 没有print命令(无论如何都没有内置在 bash 中),只有printfand echo;
  10. 你应该总是引用你的变量,除非有很好的理由不这样做。

因此,稍微改进的脚本的工作版本将是:

#!/bin/bash -
# Checks word count of each text file directory and deletes if less than certain   amount of words
# Lastly, displays number of files deleted

count=0 # Set counter to 0
limit=2000

for file in *.txt
do
     words=$(wc -w < "$file")
     if [ "$words" -lt "$limit" ]
     then
         rm -- "$file"
         ((count++))
     fi
done

echo "Number of files deleted: $count" 
Run Code Online (Sandbox Code Playgroud)

下次,我建议您在尝试使用一种语言进行编码之前先熟悉它。每种语言都有自己的规则和语法。