【问题标题】:Tee command not appending [duplicate]Tee 命令未附加 [重复]
【发布时间】:2021-08-17 20:19:50
【问题描述】:

我正在尝试编写一个名为 updateFile.sh 的 bash 脚本。目前如下:

function insertIntoFile(){
    local variable=$1
    local target=$2
    echo "${variable}" | tee -a "${target}";
}

insertIntoFile "export/ foo=bar" "~/.bash_profile"

运行bash -x ./updateFile.sh

对于输出,我得到...

...
+ echo 'export/ foo=bar'
+ tee -a '~/.bash_profile'
export/ foo=bar

然而,当我cat ~/.bash_profile

给定的字符串仍然是空的。

我试过不带斜线的导出,所以我知道不是这样,我已经挖掘了堆栈溢出,我所看到的一切似乎都表明这应该可以工作,但我不明白为什么它不是或如何解决它。

【问题讨论】:

    标签: bash


    【解决方案1】:

    正如Inian 评论的那样,您在双引号内使用波浪号:

    insertIntoFile "export/ foo=bar" "~/.bash_profile"
    

    感到惊讶的是~ 没有在双引号内展开。使用$HOME 变量或删除双引号:

    insertIntoFile "export/ foo=bar" "$HOME/.bash_profile"
    

    insertIntoFile "export/ foo=bar" ~/.bash_profile
    

    我还建议使用printf 而不是echo,因为echo 的各种实现可能会尝试解析(阅读:mangle)以-n-e 开头的“$variable”值.更改此行:

    echo "${variable}" | tee -a "${target}";
    

    到这里:

    printf '%s\n' "${variable}" | tee -a "${target}";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-15
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 2017-08-22
      • 2020-07-14
      • 2016-12-21
      相关资源
      最近更新 更多