How to execute a remote command over ssh with arguments?

前端 未结 4 715
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 20:09

In my .bashrc I define a function which I can use on the command line later:

function mycommand() {
    ssh user@123.456.789.0 cd testdir;./test         


        
4条回答
  •  广开言路
    2020-12-07 20:40

    Do it this way instead:

    function mycommand {
        ssh user@123.456.789.0 "cd testdir;./test.sh \"$1\""
    }
    

    You still have to pass the whole command as a single string, yet in that single string you need to have $1 expanded before it is sent to ssh so you need to use "" for it.

    Update

    Another proper way to do this actually is to use printf %q to properly quote the argument. This would make the argument safe to parse even if it has spaces, single quotes, double quotes, or any other character that may have a special meaning to the shell:

    function mycommand {
        printf -v __ %q "$1"
        ssh user@123.456.789.0 "cd testdir;./test.sh $__"
    }
    
    • When declaring a function with function, () is not necessary.
    • Don't comment back about it just because you're a POSIXist.

提交回复
热议问题