我正在尝试制作一个bash脚本,它计算输入中的换行数。第一个if语句(开关$0)工作正常,但我遇到的问题是试图让它在终端参数中读取文件的WC。
例如
~$/脚本.sh




(用户按CTRL+D)
此处显示字数#答案是5-工作正常
例如
~$.script1.sh厕所在这里-(5)
~$成功地从文件重定向stdin
但是
例如
~$./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

最佳答案

#!/bin/sh
set -e
if [ -t 0 ]; then
    # We are *not* reading stdin from a pipe or a redirection.
    # Get the counts from the files specified on the cmdline
    if [ "$#" -eq 0 ]; then
        echo "no files specified" >&2
        exit 1
    fi
    cat "$@" | wc
else
    # stdin is attached to a pipe or redirected from a file
    wc
fi | { read lines words chars; echo "lines=$lines words=$words chars=$chars"; }

由于shell(一些shell)在管道中使用命令行的方式,来自命令的变量只存在于大括号中。通常,解决方案是从流程替换(bash/ksh)重定向。
这个可以压扁成
#!/bin/bash
[[ -t 0 ]] && files=true || files=false
read lines words chars < <({ ! $files && cat || cat "$@"; } | wc)
echo "lines=$lines words=$words chars=$chars"

readcmd | read x的快速演示
$ x=foo; echo bar | read x; echo $x
foo
$ x=foo; read x < <(echo bar); echo $x
bar

关于linux - Bash-通过终端命令计数换行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53053143/

10-10 20:27