简体   繁体   English

无法从bash脚本中获取带有空格的SCP路径吗?

[英]Cannot SCP a path with spaces from bash script?

I have a bash script which generates an SCP command to execute. 我有一个bash脚本,该脚本生成一个SCP命令来执行。 The relevant parts of the code look like this: 代码的相关部分如下所示:

echo $COPY_CMD
$COPY_CMD

My output looks like this: 我的输出看起来像这样:

rascher@localhost:~/Desktop/video_final$ ./xfervids.sh 
scp "/media/My Book/PhotosVideos/Videos/18May2008Download/SD_VIDEO/PRG001/MOV056.MOD" rascher@192.168.1.101:./video_working/
rascher@192.168.1.101's password: 
"/media/My: No such file or directory
Book/PhotosVideos/Videos/18May2008Download/SD_VIDEO/PRG001/MOV056.MOD": No such file or directory

However, when I take line 2 of my output: scp "/media/... , copy it, and paste it into the terminal, it works. 但是,当我选择输出的第2行: scp "/media/... ,将其复制并粘贴到终端中,即可正常工作。

What am I doing wrong? 我究竟做错了什么? I have tried escaping the space in "My Book" ( "My\\ Book" ), putting two \\ characters rather than one ( "My\\\\ Book" ) but I can't get this to behave consistently. 我尝试转义“ My Book”( "My\\ Book" )中的空格,而不是一个( "My\\\\ Book" )放置两个\\字符,但是我无法使它始终如一地运行。 Help? 救命?

You have to be excruciatingly careful when there are spaces in the path names. 当路径名中有空格时,您必须格外小心。

In the context, you probably need: 在上下文中,您可能需要:

eval $COPY_CMD

You don't need quotes around the variable this time. 这次您不需要在变量周围加上引号。

You should read this discussion of how and why to avoid putting commands in variables and this discussion of the security implications of eval . 您应该阅读有关如何以及为什么避免将命令放在变量中的讨论 ,以及有关eval的安全隐患的讨论

One reason you may want to use variables in this way is to log or display the actions taken by a script. 您可能希望以这种方式使用变量的原因之一是记录或显示脚本执行的操作。 Problems occur with being able to properly quote or escape spaces, etc., as you have discovered. 正如您所发现的那样,能够正确引用或转义空格等问题会出现。 One way to do what you may want is to use set -x and set +x to turn this type of output on and off at various points in your script. 一种执行所需操作的方法是使用set -xset +x在脚本的各个位置打开和关闭这种类型的输出。

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

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