或者,有关强大的文件名处理和在 shell 脚本中传递的其他字符串的介绍性指南。
我写了一个 shell 脚本,它在大多数情况下运行良好。但它在某些输入(例如某些文件名)上窒息。
我遇到了如下问题:
hello world
,它被视为两个单独的文件hello
和world
.\[*?
,它们会被一些文本替换,这实际上是文件的名称。'
(或双引号"
),在那之后事情变得很奇怪。\
分隔符)。这是怎么回事,我该如何解决?
$ ls -l /tmp/test/my\ dir/
total 0
Run Code Online (Sandbox Code Playgroud)
我想知道为什么以下运行上述命令的方法失败或成功?
$ abc='ls -l "/tmp/test/my dir"'
$ $abc
ls: cannot access '"/tmp/test/my': No such file or directory
ls: cannot access 'dir"': No such file or directory
$ "$abc"
bash: ls -l "/tmp/test/my dir": No such file or directory
$ bash -c $abc
'my dir'
$ bash -c "$abc"
total 0
$ eval $abc
total 0
$ eval "$abc"
total 0
Run Code Online (Sandbox Code Playgroud) 鉴于这些文件名:
$ ls -1
file
file name
otherfile
Run Code Online (Sandbox Code Playgroud)
bash
本身对于嵌入的空白完全没问题:
$ for file in *; do echo "$file"; done
file
file name
otherfile
$ select file in *; do echo "$file"; done
1) file
2) file name
3) otherfile
#?
Run Code Online (Sandbox Code Playgroud)
但是,有时我可能不想处理每个文件,甚至不希望使用严格的 in $PWD
,这是find
进来的地方。名义上也处理空格:
$ find -type f -name file\*
./file
./file name
./directory/file
./directory/file name
Run Code Online (Sandbox Code Playgroud)
我正在尝试编造这个scriptlet的 whispace-safe 版本,它将获取输出find
并将其呈现到select
:
$ select file in $(find -type f -name file); do echo $file; break; …
Run Code Online (Sandbox Code Playgroud)