【问题标题】:Echoing an echo argument in Bash在 Bash 中回显 echo 参数
【发布时间】:2018-01-15 21:56:30
【问题描述】:

这是显示问题的代码:

#!/bin/bash

function char() {
    local char="$(echo $1 | cut -c2)"    # Gets second character from argument.
    echo $char
}

char -a                                  # Outputs 'a'.
char -e                                  # Or 'char -n' outputs nothing.

我希望这段代码输出 [ 'a', 'e' ] 而不是 [ 'a', nothing ]。

我认为问题出在 echo $1 上。我的问题有点类似于one。但似乎大多数解决方案都不适合我。我认为 Bash 从那个问题的版本中改变了它的行为:'3.00.15(1)-release (x86_64-redhat-linux-gnu)'。

我的 Bash 版本是“4.3.30(1)-release (i586-pc-linux-gnu)”。我试过了:

echo x-e                                 # Outputs 'x-e'.
echo -- -e                               # Outputs '-- -e'.
echo "-e "                               # Outputs '-e'.

echo "$1" 是唯一有效的“hack”。但我觉得这不是最好的做法。

附: 我个人觉得这很有趣。感谢您对此的任何想法。

【问题讨论】:

    标签: string bash unix echo bash4


    【解决方案1】:

    -eecho 解释的某些版本的标志。这里的解决方案是不要使用echo,而是使用printf

    printf '%s' "$1" | cut -c2
    

    来自help echo bash:

    Options:
     -n        do not append a newline
     -e        enable interpretation of the following backslash escapes
     -E        explicitly suppress interpretation of backslash escapes
    

    因此,当变量扩展并且您尝试运行 echo -e 时,它不会回显字符串 -e,而是告诉 echo 使反斜杠表示转义序列。

    如需对Why printf is better than echo 进行深入讨论,请阅读那里的优秀答案。

    如果您尝试在此处处理命令行选项,您可能会考虑其他方法。喜欢 getopts 或阅读 here 了解一些不错的选择

    【讨论】:

    • 另外,在这种特殊情况下,您可以使用子字符串扩展来获取第二个字符,而不是使用cutprintf '%s' "${1:1:1}"(三个“1”的意思是,第一个参数,开始在字符 #1(#0 是第一个字符)处,只返回一个字符。)取决于如何使用它,您可能还想使用 printf '%s\n' 在输出中添加换行符。
    • 问题不在于使用printf 而不是echo。但无论如何,你的答案是唯一的。
    • @GordonDavisson ,你甚至不需要使用 printf 在你的情况下,local char=${1:1:1} 就足够了。
    • 另外,当它需要将一些变量的内容传递给命令时,我建议使用"here string" 像这样:local char=$(cut -c2 <<< "$1") 而不是 echo 或 printf。
    • @YooryN。好点子;进行直接分配(没有$( ) 的东西)可以进一步简化它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 2013-10-27
    • 2011-11-16
    • 1970-01-01
    相关资源
    最近更新 更多