我是bash的初学者。该脚本必须执行以查找请求的文件并检查权限。并在特定文件中搜索字符串“ to”
#!/bin/bash
if [ ! -e "$1"]
then
echo "The file does not exist!"
exit 1
elif [ ! -r "$1"]
then
echo "You do not have read permission on this file!"
exit2
fi
count=0
while read line do
for word in $line do
if [ $word = "to" ]
then
count='expr$count+1'
fi
done
done<$1
echo "The word 'to' occurred $count times in your file"
答案 0 :(得分:0)
在https://www.shellcheck.net/上出现语法错误时,请始终测试脚本。
它可以说明您在所有if
条件下都缺少空格:
if [ ! -e "$1"]
VS
if [ ! -e "$1" ]
# ^
# mandatory
还有一个小问题,让您在shellcheck中发现自己。
这种算术是完全错误的。请考虑:
while IFS= read -r line do
for word in $line; do
if [[ $word == to ]]; then
((++count))
fi
done
done < "$1"
echo "The word 'to' occurred $count times in your file"
how to read a file line by line
((...))
是一种算术命令,如果表达式非零,则返回退出状态0;如果表达式为零,则返回退出状态1。如果需要副作用(赋值),也可以用作“ let”的同义词。参见http://mywiki.wooledge.org/ArithmeticExpression
[[
是bash关键字,类似于[
命令(但比[[
命令更强大)。请参阅http://mywiki.wooledge.org/BashFAQ/031和http://mywiki.wooledge.org/BashGuide/TestsAndConditionals。除非您为POSIX sh编写,否则我们建议使用B / Compile / fullClasspath
。
每个包含空格/元字符和每一个扩展的文字都用“双引号”:“ $ var”,“ $(command” $ var“)”,“ $ {array [@]}” ,“ a和b”。使用'单引号'表示代码或使用$表示:'Costs $ 5 US',ssh主机'echo“ $ HOSTNAME”'。参见http://mywiki.wooledge.org/Quotes,http://mywiki.wooledge.org/Arguments和http://wiki.bash-hackers.org/syntax/words