正确计算bash变量的行数

lin*_*ndy 6 bash shell wc

我需要计算给定变量的行数.例如,我需要找到有多少行VAR,在哪里VAR=$(git log -n 10 --format="%s").

我试过echo "$VAR" | wc -l),确实有效,但如果VAR是空的,就是打印1,这是错误的.这有解决方法吗?比使用if子句检查变量是否为空更好...(可能添加一行并从返回值中减去1?).

jm6*_*666 13

wc计数换行字符的数量.您可以使用grep -c '^'计数线.您可以看到与以下区别:

#!/bin/bash

count_it() {
    echo "Variablie contains $2: ==>$1<=="
    echo -n 'grep:'; echo -n "$1" | grep -c '^'
    echo -n 'wc  :'; echo -n "$1" | wc -l
    echo
}

VAR=''
count_it "$VAR" "empty variable"

VAR='one line'
count_it "$VAR" "one line without \n at the end"

VAR='line1
'
count_it "$VAR" "one line with \n at the end"

VAR='line1
line2'
count_it "$VAR" "two lines without \n at the end"

VAR='line1
line2
'
count_it "$VAR" "two lines with \n at the end"
Run Code Online (Sandbox Code Playgroud)

什么产生:

Variablie contains empty variable: ==><==
grep:0
wc  :       0

Variablie contains one line without \n at the end: ==>one line<==
grep:1
wc  :       0

Variablie contains one line with \n at the end: ==>line1
<==
grep:1
wc  :       1

Variablie contains two lines without \n at the end: ==>line1
line2<==
grep:2
wc  :       1

Variablie contains two lines with \n at the end: ==>line1
line2
<==
grep:2
wc  :       2
Run Code Online (Sandbox Code Playgroud)


nem*_*emo 6

你总是可以有条件地写它:

[ -n "$VAR" ] && echo "$VAR" | wc -l || echo 0
Run Code Online (Sandbox Code Playgroud)

这将检查是否$VAR有内容并采取相应行动.


gni*_*urf 5

对于纯粹的bash解决方案:不是将git命令的输出放入变量(可以说是丑陋),而是将其放在一个数组中,每个字段一行:

mapfile -t ary < <(git log -n 10 --format="%s")
Run Code Online (Sandbox Code Playgroud)

那么你只需要计算数组中的字段数ary:

echo "${#ary[@]}"
Run Code Online (Sandbox Code Playgroud)

如果您需要检索第5个提交消息,此设计还将使您的生活更简单:

echo "${ary[4]}"
Run Code Online (Sandbox Code Playgroud)