【问题标题】:How to improve this FTP (shell) function?如何改进这个 FTP (shell) 功能?
【发布时间】:2011-07-30 02:48:27
【问题描述】:

我有大量使用以下函数的脚本:

# Copies files over using FTP.
# Configurations set at the beggining of the script
# @param    $1 = FTP Host
#           $2 = FTP User
#           $3 = FTP User password
#           $4 = Source file name
#           $5 = destination directory
#           $6 = local directory
doftp() {
    log_message_file "INFO" "Starting FTP"

    ftp_hst=$1
    ftp_usr=$2
    ftp_pwd=$3
    sourcefile=$4
    destdir=$5
    locdir=$6

    ftp -nv $FTPH << EOF 2> ftp.err.$$
quote USER $ftp_usr
quote PASS $ftp_pwd
cd $destdir
lcd $locdir
bin

put $sourcefile

bye
EOF

    if [ "$(wc ftp.err.$$|cut -d" " -f8)" != 0 ] ; then
        log_message_file "ERROR" "Problem uploading files: $(cat  ftp.err.$$)"
    else
        log_message_file "INFO" "FTP finished"
    fi
    rm ftp.err.$$
}

它工作,它的工作,除非 ftp 失败。对我来说幸运的是,脚本非常精确,FTP 几乎从不失败。但这是难得的时刻之一,人们有机会(时间)返回并查看 TODO 列表中标记的代码。唯一的问题是我不太确定如何改进它......我会向你们提出关于在那里改变什么的建议。

一个明显的问题是从 ftp 解析错误,这完全是蹩脚的。但我也会考虑函数的其他部分:)

值得一提的是这是在 AIX 服务器上运行的吗?哦,不,我不能使用 SFTP :(

感谢您的任何意见!

ps.:log_message_file 只是一个基本的日志记录...对功能没有影响。

【问题讨论】:

  • 也许这更适合 codereview.stackexchange.com
  • 您使用哪种外壳?例如对于 ksh 和 bash,$(&lt; filename) 可以替换 $(cat filename)
  • 谢谢!是克什。但改变真的值得吗?我的意思是,我猜cat 让它更跨平台,对吧?

标签: shell ftp


【解决方案1】:
  • 良好的文档
  • 好的变量名
  • 很好的缩进,你可能想了解
  • 很好地使用带有 $$ 的 tmp 文件名(根据使用此函数的程度,您可能希望将父脚本名称附加为 tmp 名称的一部分,以进一步消除歧义,但优先级较低)
  • 善用 $(cat ftp.err.$$) 即实际显示错误消息,而不仅仅是“发生错误”之类的消息(我一直看到这个,什么错误?什么是味精?!)

  • 1234563检查您的 mput ${fileNames} 变量是否仍按预期工作。
  • 可能要考虑改进的一个地方是使用 case 语句来解析 STDERR 输出,但同样,额外的好处可能不值得未来的维护成本。

    李>
errMsgs="$(cat ftp.err.$$)"

case "${errMsgs}" in
    *warningStrings* ) print "warning found, msg was ${errMsg} ;;
    *errorStrings* ) print "error found, msg was ${errMsg} ;;
    *fatalStrings* ) pring "fatal error found, can't continue, msg was ${errMsg} ;;
esac

我希望这会有所帮助。

【讨论】:

  • 好东西!感谢您的提示!我一定会考虑case!唯一的问题是,要这样做,我必须知道 FTP 错误中的所有错误字符串......哪种难......对吗?哦,还有如何识别heredoc的好方法!谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 2022-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多