繁体   English   中英

bash脚本:echo >>返回错误“无此文件或目录”

[英]bash script: echo >> returns error “No such file or directory”

为什么不使用此代码?

#!/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”有关。

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

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

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

(摘自man bash ,重点是我的)

因此,bash不能在变量值中扩展波浪号。 如果您确实在分配中直接直接分配了值,请不要使用引号:代号扩展会发生在分配的值上。

test=~/.test

如果文件名需要加引号,请保持开头不超过引号的斜杠:

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

下面的表达式不起作用

test=~"/.test"
给出.test文件绝对路径的最佳方法。 例如
  测试= “/ home / user中/。测试” 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM