bash 脚本:echo >> 返回错误“没有这样的文件或目录”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36623731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:30:06  来源:igfitidea点击:

bash script: echo >> returns error "No such file or directory"

bashshellappendecho

提问by p4x

Why isn't working this code?

为什么不工作此代码?

#!/bin/bash

test="~/.test"

function fn_append () {

    echo "check vars:   ···   ··· "
    echo "check comm: echo \"\" >> "
        #this returns "No such file or directory"
    echo  >> 
    echo  >> 
    echo  >> ""
        #this creates file named 
    echo  >> ''
        #this works (but it isn't enough)
    echo  >> ~/.test
        #this is the command Im trying to create.
    #echo "alias ll='ls -lstra'" >> ~/.test
}

fn_append ${test} "alias ll='ls -lstra'"

Executing outputs this:

执行输出这个:

check vars: ~/.test  ···  ~/.test ··· alias ll='ls -lstra'
check comm: echo "alias ll='ls -lstra'" >> ~/.test
./test.sh: line 9: ~/.test: No such file or directory
./test.sh: line 10: ~/.test: No such file or directory
./test.sh: line 11: ~/.test: No such file or directory

The file does exist (though even if it doesn't the script should work anyway) and I have permissions. The command works on terminal and hardcoded on the script. What fails is something related to the "$1".

该文件确实存在(尽管即使它不存在,脚本也应该可以工作)并且我有权限。该命令在终端上工作并在脚本上硬编码。失败的是与“$ 1”有关的东西。

P.D: I know there are other ways to append a file. I've been using them for now, but still I would like to fix this code or at least to know why it isn't working.

PD:我知道还有其他方法可以附加文件。我现在一直在使用它们,但我仍然想修复此代码或至少知道它为什么不起作用。

回答by choroba

Variable expansion happens later than tilde expansion:

变量扩展发生在波浪号扩展之后:

The order of expansions is: brace expansion, tildeexpansion, parameter, variableand arithmetic expansion and command substitution (done in a left-to-right fashion), word splitting, and pathname expansion.

扩展的顺序是:大括号扩展、波浪号扩展、参数、变量和算术扩展以及命令替换(以从左到右的方式完成)、分词和路径名扩展。

(from man bash, emphasis mine)

(来自man bash,强调我的)

Therefore, bash can't expand the tilde in the variable value. If you really assign the value directly in an assignment, don't use the quotes: tilde expansion happens on the assigned value.

因此,bash 无法扩展变量值中的波浪号。如果你真的在赋值中直接赋值,不要使用引号:波浪号扩展发生在赋值上。

test=~/.test

If the filename needs quoting, keep the beginning up to the first slash out of the quotes:

如果文件名需要引用,请将开头保留到引号中的第一个斜杠:

test=~username/'path that/needs quoting'

回答by Mahadev Patil

Below expression won't work

下面的表达式不起作用

test=~"/.test"
为 .test 文件提供绝对路径的最佳方法。例如
test="/home/user/.test"