bash script to run lftp with ftp path

点点圈 提交于 2019-12-12 03:32:32

问题


I'm trying to write a bash alias/function that takes an ftp path and runs lftp to pget the file.

Given a remote path, with spaces encoded as %20 like:

sftp://ftp.example.com/Some%20Folder/BigFile.mov

I have this snippet to clean up the %20 and server part of the URL:

echo $1 | sed 's/%20/ /g' | sed 's/sftp:\/\/ftp.example.com//g';

which gives me

/Some Folder/BigFile.mov

Now I need to run this through lftp like this:

lftp sftp://ftp.example.com -u user,pass -e "pget -cn10 '/Some Folder/BigFile.mov'"

I want to create an alias with a function to this command, let's call it lget, so I can just use the original URL:

lget "sftp://ftp.example.com/Some%20Folder/BigFile.mov"

The solution here should like something like

alias lget='function _lget(){ lftp ... };_lget'

But I get completely lost as to how to include the argument in the function, have it processed through sed, and how to handle the nested quotation marks.

I probably need some backticks ...


回答1:


Something like this?

lget () {
    local filename=${1#sftp://ftp.example.com}
    lftp sftp://ftp.example.com -u user,pass -e "pget -cn10 '${filename//%20/ }'"
}

I don't see why you would want to create a function with a useless name only to be able to assign the useful name to an alias which simply calls the function (though this seems to be the norm in some circles, for reasons unknown to me).

You don't need sed because Bash contains built-in functions for string substitution. If you need this to be portable to POSIX shell, which lacks the ${variable//global/replacement} functionality (and the local keyword), take care to properly quote the string you pass to sed. (The ${variable#prefix} syntax to retrieve the value of a variable with a prefix removed is available in POSIX shell. Oh, and for the record, a single sed script can perform multiple substitutions; sed -e 's/foo/bar/' -e 's/baz/quux/g'.)



来源:https://stackoverflow.com/questions/35771955/bash-script-to-run-lftp-with-ftp-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!