echo命令产生了额外的空格

时间:2018-12-07 13:55:05

标签: macos shell zsh

  

环境:macOS 10.14

     

shell:zsh

“ Linux命令行”一书中有几行代码

#!/bin/bash
while [[ -n $1 ]]; do
        if [[ -r $1 ]]; then
                max_word=
                max_len=0
                for i in $(strings $1); do
                        len=$(echo $i | wc -c)
                        if (( len > max_len )); then
                                max_len=$len
                                max_word=$i
                        fi
                done
                echo "$1: '$max_word' ($max_len characters)"
        fi
        shift
done

我用命令运行了代码

hello hello

hello是包含代码且可执行的文件。该程序很简单。但是,输出为:

hello: 'max_len=$len' (      13 characters)

在离开(后,您会看到一些多余的空格。我不知道为什么,也没有通过Google获得任何解决方案。

2 个答案:

答案 0 :(得分:4)

为什么要产生额外的过程? chart.setTouchEnabled(false); chart.setPinchZoom(false); chart.setDoubleTapToZoomEnabled(false); 应该更有效地为您提供字符串的长度。

答案 1 :(得分:1)

在Linux上不会发生,但是我敢打赌wc -c在Mac上正在打印“ 13”而不是“ 13”。 解决的方法之一就是改变

len=$(echo $i | wc -c)

len=($(echo $i | wc -c))

此解决方法使用数组语法,“ 13”将被解释为数组,因此bash将解析“(13)”,从而得到[“ 13”]数组。 len将包含一个数组,但是当bash用作普通变量时,它将使用第一个元素,在这种情况下,bash将使用wc -c输出的剥离版本。