p4x*_*p4x 2 bash shell append echo
为什么不使用这段代码?
#!/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'"
Run Code Online (Sandbox Code Playgroud)
执行输出:
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
Run Code Online (Sandbox Code Playgroud)
该文件确实存在(即使它不是脚本应该工作),我有权限.该命令适用于终端并在脚本上进行硬编码.失败的是与"1美元"相关的事情.
PD:我知道还有其他方法可以附加文件.我一直在使用它们,但我仍然希望修复此代码或者至少知道它为什么不起作用.
变量扩展比波浪扩展晚发生:
扩展的顺序是:括号扩展,波浪扩展,参数,变量 和算术扩展和命令替换(以从左到右的方式完成),单词拆分和路径名扩展.
(来自man bash
,强调我的)
因此,bash不能扩展变量值中的波浪号.如果您确实在赋值中直接赋值,请不要使用引号:波形扩展在指定的值上发生.
test=~/.test
Run Code Online (Sandbox Code Playgroud)
如果文件名需要引用,请将开头保持为引号的第一个斜杠:
test=~username/'path that/needs quoting'
Run Code Online (Sandbox Code Playgroud)