为什么不在文件路径中使用bash转义空格或荣誉引号?

low*_*tex -1 bash whitespace filepath

我在我的路径中将以下脚本保存为"lspkg":

#!/bin/bash
args=("$@")

for item in ${args[@]}; do
    echo "$item"
done
Run Code Online (Sandbox Code Playgroud)

当我运行时lspkg /absolute/path/to/file,它按预期工作,打印路径.但是,以下行为给我带来了很多麻烦:

转义路径中的空格并没有真正逃离空间:

$ lspkg /absolute/path/to/file\ with\ spaces
/absolute/path/to/file\
with\
spaces
Run Code Online (Sandbox Code Playgroud)

将路径放在引号中不会使bash将其视为单个字符串:

$ lspkg "/absolute/path/to/file with spaces"
"/absolute/path/to/file
with
spaces"
Run Code Online (Sandbox Code Playgroud)

为什么会这样,这个问题怎么解决?

anu*_*ava 5

您的脚本中缺少重要的引号,请使用:

#!/bin/bash
args=("$@")

for item in "${args[@]}"; do
    echo "$item"
done
Run Code Online (Sandbox Code Playgroud)

"${args[@]}"shell中没有引号正在扩展并将其视为多个参数.