【问题标题】:bash script: echo >> returns error "No such file or directory"bash 脚本:echo >> 返回错误“没有这样的文件或目录”
【发布时间】:2016-04-14 12:52:54
【问题描述】:

为什么这段代码不起作用?

#!/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”相关的东西。

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

【问题讨论】:

    标签: bash shell append echo


    【解决方案1】:

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

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

    (来自man bash,强调我的)

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

    test=~/.test
    

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

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

    【讨论】:

    • 或者至少,将~ 留在引号中:test=~"/.test"(用于需要引用空格的时间)。
    • @chepner:那行不通。 test=~/'.test' 确实如此。
    • 呵呵,没注意到。
    • @chepner:我也没有,但现在测试了。由man bash 中的波浪号扩展的第一段解释。
    【解决方案2】:

    下面的表达式不起作用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-16
      • 2020-05-09
      • 2017-08-06
      • 2016-06-25
      • 2014-02-13
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多