source命令不使用变量或带引号的字符串

Cri*_*rez 0 bash scripting

我遇到了这个问题.

如果我做...

source /Users/cristian/Proyectos/MikroTik\ Updater/sources/testfile
Run Code Online (Sandbox Code Playgroud)

它确实有效

如果我做...

source "/Users/cristian/Proyectos/MikroTik\ Updater/sources/testfile"
Run Code Online (Sandbox Code Playgroud)

它没有

问题是我正在使用一个变量,其中包含一个前面有一些步骤的路径

所以这...

mypath="/Users/cristian/Proyectos/MikroTik\ Updater/sources/testfile"
source $mypath
Run Code Online (Sandbox Code Playgroud)

不起作用

我发现了一个解决方法...

eval "source $mypath"
Run Code Online (Sandbox Code Playgroud)

但当然这是一个很大的安全漏洞,因为文件名来自一个参数

我能做什么?

编辑:

正如您在代码中看到的,我回显文件名,然后尝试获取它

updaterpath="$( cd "$(dirname "$0")" ; pwd -P | sed  's/ /\\ /g' )"
sourcefile="$updaterpath/sources/$1"

echo $sourcefile
source $sourcefile
Run Code Online (Sandbox Code Playgroud)

在输出中,我得到了正确的路径回显,并source说出它的错误不存在!有趣的是,无论我cat是那个文件,我都可以看到内容,所以文件路径是正确的!

/Users/cristian/Proyectos/MikroTik\ Updater/sources/testfile
/Users/cristian/Proyectos/MikroTik Updater/updater.sh: line 7: /Users/cristian/Proyectos/MikroTik\: No such file or directory
Run Code Online (Sandbox Code Playgroud)

Cha*_*ffy 5

您的原始问题不包括错误的代码:

### THIS IS BROKEN: the backslashes added by sed are literal, not syntactic
path=$(cd "$(dirname "$0")"; pwd -P | sed 's/ /\\ /g')
source $path/sources/$1
Run Code Online (Sandbox Code Playgroud)

sed是你的问题的根源.摆脱它:

### THIS IS CORRECT: The syntactic quotes mean no backslashes are needed.
# ...also handles the case when the cd fails more gracefully.
path=$(cd "$(dirname "$0")" && pwd -P) || exit
source "$path/sources/$1"
Run Code Online (Sandbox Code Playgroud)

......或者,甚至更好:

source "${BASH_SOURCE%/*}/sources/$1"
Run Code Online (Sandbox Code Playgroud)

反斜杠仅在解析为语法时才有意义.字符串扩展的结果不会通过这些解析步骤.这与使用字符串引号不能用于在字符串中构建命令的原因相同,如BashFAQ#50中所述.