【发布时间】:2018-10-29 20:13:29
【问题描述】:
我正在尝试制作一个 bash 脚本来计算输入中的换行符。第一个 if 语句(switch $0)工作正常,但我遇到的问题是试图让它读取终端参数中文件的 WC。
例如 ~$ ./script.sh
1
2
3
4
(用户按下 CTRL+D)
在此处显示字数 # 答案为 5 - 工作正常
例如
~$ .script1.sh 这里是厕所-(5) ~$ 成功从文件重定向标准输入 但是
例如
~$ ./script1.sh script1.sh script2.sh 此处为 script1.sh 显示 WC 此处为 script2.sh 显示 WC 没什么 ~$ 我认为的问题是第二个 if 语句,而不是在终端中执行脚本,而是转到 if 语句并等待用户输入并且它没有返回 echo 语句。 任何帮助将不胜感激,因为我无法弄清楚为什么没有 ~$
#!/bin/bash
#!/bin/sh
read filename ## read provided filename
USAGE="Usage: $0 $1 $2..." ## switch statement
if [ "$#" == "0" ]; then
declare -i lines=0 words=0 chars=0
while IFS= read -r line; do
((lines++))
array=($line)
((words += ${#array[@]}))
((chars += ${#line} + 1)) # add 1 for the newline
done < /dev/stdin
fi
echo "$lines $words $chars $filename" ## filename doesn't print, just filler
### problem if statement####
if [ "$#" != "0" ]; then # space between [] IS VERY IMPORTANT
declare -i lines=0 words=0 chars=0
while IFS= read -r line; do
lines=$( grep -c '\n'<"filename") ##should use grep -c to compare only new lines in the filename. assign to variable line
words=$( grep -c '\n'<"filename")
chars=$( grep -c '\n'<"filename")
echo "$lines $words $chars"
#lets user press CTRL+D to end script and count the WC
fi
【问题讨论】:
-
在变量赋值中,
=周围不能有空格。 -
啊,谢谢!我会在上面修复它。