bash: 文件名中包含空格时会被截断

huangapple go评论83阅读模式
英文:

bash: filename with space gets truncated

问题

#!/bin/bash

documents=("/datalog/AB errors.txt");

/usr/bin/bash /home/user/download.sh "${documents[*]}";

download.sh会SCP到服务器并下载documents,但在上面的情况下,文件名中有空格,这会导致它寻找/datalog/AB而不是AB errors.txt文件。

我认为用双引号括起来可以解决文件名中的空格问题。我还尝试过AB\ errors.txt,但这导致整个bash脚本都无法运行。

英文:
#!/bin/bash

documents=("/datalog/AB errors.txt");

/usr/bin/bash /home/user/download.sh "${documents[*]}"

the download.sh SCPs into a server and downloads documents but in the case above there is a space in the file name which leads it to seek /datalog/AB instead of AB errors.txt file.

I thought surrounding in double quotes fixes the space in filename issue. I also tried AB\ errors.txt but that caused the entire bash script to not run.

答案1

得分: 0

以下是已翻译的内容:

表单

documents="/datalog/AB errors.txt"

是不好的形式(将字符串转换为数组!!!)。 赋值的正确形式是

documents="/datalog/AB errors.txt"

始终假定完整路径变量可能包含空格或其他字符,并始终对此类变量实例进行双引号引用,即

ls "${variable}" .

正如Gordon Davisson所说,您必须在脚本/编程的每个层面以这种方式编写代码,以确保嵌入的特殊字符不会导致意外结果。

英文:

The form

documents=("/datalog/AB errors.txt")

is bad form (turning string into an array !!!). The correct form for assignment is

documents="/datalog/AB errors.txt"

Always assume full-path variables can have spaces or other characters, and always double-quote such variable instantiations, i.e.

ls "${variable}" .

As Gordon Davisson said, you must code in this fashion at every level of scripting/programming to ensure the embedded special characters don't lead to unexpected results.

huangapple
  • 本文由 发表于 2023年2月14日 06:31:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441802.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定