Bash脚本:echo >> 返回“没有此文件或目录”错误

5
为什么这段代码无法运行?
#!/bin/bash

test="~/.test"

function fn_append () {

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

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

执行后会产生以下输出:

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

文件是存在的(即使文件不存在,脚本也应该能够正常工作),而且我有权限。此命令在终端上和硬编码在脚本中都可以正常工作。失败的原因与"$1"相关。
附注:我知道有其他方法来追加文件。我现在一直在使用它们,但我仍然想修复这个代码或者至少知道为什么它不起作用。
2个回答

7
变量扩展发生在tilde扩展之后:
扩展顺序为:大括号扩展,tilde扩展,参数,变量和算术扩展以及命令替换(按从左到右的顺序进行),单词分割和路径名扩展。
(来自man bash,强调我的)
因此,bash无法扩展变量值中的tilde。如果您确实直接在赋值中分配值,请不要使用引号:tilde扩展会在分配的值上进行。
test=~/.test

如果文件名需要引用,请将引号保留在第一个斜杠之前的开头:
test=~username/'path that/needs quoting'

或者至少在引号中省略~test=~"/.test"(用于需要引用空格的情况)。 - chepner
2
@chepner:那样是行不通的。但是test=~/'.test'可以。 - choroba
哦,从来没有注意到过。 - chepner
@chepner:我也没用过,但现在测试了一下。在man bash的第一段中有波浪号展开的解释。 - choroba

-1

以下表达式无法工作

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接