简体   繁体   English

bash脚本中的空格

[英]spaces in bash scripts

So, I've been trying for a while and this really won't work. 因此,我已经尝试了一段时间,但这确实行不通。 I'm trying to write a script that will concatenate many pdf files into one without the tedium of specifying them at the command-line interface (they all have similar names). 我正在尝试编写一个脚本,该脚本将许多pdf文件连接成一个脚本,而没有在命令行界面中指定它们的繁琐工作(它们都具有相似的名称)。

#!/bin/bash 

i=1 
list="science.pdf" 
outputfile="file.pdf" 

while [ $i -le 3 ]; do 
    file="science (${i}).pdf" 
    list="$list $file" 
    let i=i+1 
done 

pdftk $list cat output $outputfile

And this is my output: 这是我的输出:

sean@taylor:~/Downloads/understanding/s0$ ./unite.sh 
Error: Failed to open PDF file: 
   science
Error: Failed to open PDF file: 
   (1).pdf
Error: Failed to open PDF file: 
   science
Error: Failed to open PDF file: 
   (2).pdf
Error: Failed to open PDF file: 
   science
Error: Failed to open PDF file: 
   (3).pdf
Errors encountered.  No output created.
Done.  Input errors, so no output created.

I figure that somehow the script thinks that the files should be split up wherever therre's a space, but I've tried both a backslash before the space (\\ ) and surrounding the file name with a quote (\\") to no avail. 我认为脚本以某种方式认为应该在有空格的任何地方拆分文件,但是我已经尝试了在空格(\\)之前使用反斜杠以及在文件名两边加上引号(\\“)都无济于事。

Can anyone help please? 有人可以帮忙吗?

Don't append the filenames to a string. 不要将文件名附加到字符串中。 Use an array instead: 改用数组:

i=1 
list=( "science.pdf" )
outputfile="file.pdf" 

while [ $i -le 3 ]; do 
    file="science (${i}).pdf" 
    list+=( "$file" )
    let i=i+1 
done 

pdftk "${list[@]}" cat output $outputfile

You can also simplify your script further by using a for-loop as shown below: 您还可以使用如下所示的for循环进一步简化脚本:

list=( "science.pdf" )
for (( i=1; i<=3; i++ )); do
    file="science (${i}).pdf"
    list+=( "$file" )
done
pdftk "${list[@]}" cat output $outputfile

When you execute your final command 当您执行最终命令时

pdftk $list cat output $outputfile

The $list variable is no longer quoted, ie, what is actually being executed is $ list变量不再被引用,即实际执行的是

pdftk science.pdf science (1).pdf ... science (3).pdf cat output file.pdf

You need to super-quote your $list variable. 您需要超级引用$ list变量。 Try: 尝试:

while [ $i -le 3 ]; do 
    file="science (${i}).pdf" 
    list="$list \"$file\""
    let i=i+1 
done

You may need to use a different method of concatenating variables as your loop will probably continuously unquote the previously concatenated values. 您可能需要使用其他连接变量的方法,因为循环可能会连续取消对先前连接值的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM