如何将 if 语句放入 lftp 块中

How to put if statement inside a lftp block

我正在编写 bash 脚本以使用 lftp 从 ftp 服务器下载文件。我想根据第二个输入参数删除文件。

#!/bin/bash

cd 

lftp -u found,e48RgK7s sftp://ftp.xxx.org << EOF
set xfer:clobber on
mget *.xml
if [  = "prod"]; then
  echo "Production mode. Deleting files"
  mrm *.xml
else
  echo "Non-prod mode. Keeping files"
fi
EOF

但是,在 EOF 之前的 lftp 块中不允许使用 if 语句。

Unknown command `if'.
Unknown command `then'.
Usage: rm [-r] [-f] files...
Unknown command `else'.

如何在这样的块中嵌入 if 语句?

命令替换即可:

#!/bin/bash

cd "" || exit
mode=

lftp -u found,e48RgK7s sftp://ftp.xxx.org << EOF
set xfer:clobber on
mget *.xml
$(
    if [ "$mode" = "prod" ]; then
      echo "Production mode. Deleting." >&2 # this is logging (because of >&2)
      echo "mrm *.xml"                      # this is substituted into the heredoc
    else
      echo "Non-prod mode. Keeping files" >&2
    fi
)
EOF

请注意,在 heredoc 的替换中,我们将日志消息路由到 stderr,而不是 stdout。这是必不可少的,因为 stdout 上的所有内容都变成了替换为发送到 lftp.

的 heredoc 的命令

命令替换的其他注意事项也适用:它们 运行 在子 shell 中,因此在命令替换内进行的分配将不适用于它之外,并且启动它们会产生性能成本。


一种更有效的方法是将条件组件存储在一个变量中,并在 heredoc 中展开它:

case $mode in
  prod)
    echo "Production mode. Deleting files" >&2
    post_get_command='mget *.xml'
    ;;
  *)
    echo "Non-production mode. Keeping files" >&2
    post_get_command=
    ;;
esac

lftp ... <<EOF
set xfer:clobber on
mget *.xml
$post_get_command
EOF