Linux 带变量的 lftp mv 命令

Linux lftp mv command with variable

我正在尝试从 txt 文件中读取文件名并将 FTP 服务器中的文件从一个文件夹移动到另一个文件夹。我有以下命令

grep '.rar' /home/xxxxx/public_html/xxxx/download.txt | while read -r line ; do lftp -e 'set net:timeout 20; mv "Folder Name/${line}" "Folder Name/tmp/${OUTPUT}"; bye' -u username,password ftps://11.11.11.11:990 ; done

但是,${$line} 变量没有被值替换,FTP 服务器显示

file/directory not found (Folder Name/${line})

如有指点,将不胜感激。 (如果有帮助,我正在使用 Centos 6.5)。

您将整个命令用单引号括起来,这可以防止 bash 参数在其中扩展。您可以通过反转单引号和双引号来修复该部分,如下所示:

grep '.rar' /home/xxxxx/public_html/xxxx/download.txt | while read -r line ; do lftp -e "set net:timeout 20; mv 'Folder Name/${line}' 'Folder Name/tmp/${OUTPUT}'; bye" -u username,password ftps://11.11.11.11:990 ; done

假设您没有包含换行符或单引号的文件,我希望这应该有效。

为了防止出现特殊字符,您可以使用 printf 而不是像这样直接扩展:

grep '.rar' /home/xxxxx/public_html/xxxx/download.txt | while read -r line ; do lftp -e "set net:timeout 20; mv '$(printf 'Folder Name/%q' "${line}")' '$(printf 'Folder Name/tmp/%q' "${OUTPUT}")'; bye" -u username,password ftps://11.11.11.11:990 ; done

因为我们可以使用printf%q来打印一个quoted/escaped字符串,可以在下一层命令中使用