或者,有关强大的文件名处理和在 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) 不久前我发现了一些从文件中读取输入的代码,我相信来自 Stack Exchange,我能够适应我的需求:
while read -r line || [[ -n "$line" ]]; do
if [[ $line != "" ]]
then
((x++));
echo "$x: $line"
<then do something with $line>
fi
done < "$1"
Run Code Online (Sandbox Code Playgroud)
我现在正在检查我的脚本并试图了解它在做什么......我不明白这个语句在做什么:
while read -r line || [[ -n "$line" ]];
我知道 -r 选项表示我们正在将原始文本读入行,但我|| [[ -n "$line" ]]
对语句的部分感到困惑。有人可以解释一下这是在做什么吗?