Search code examples
linuxscp

Is it possible to create an empty file using scp?


In *nix, I can create an empty file using cp:

cp /dev/null ~/emptyfile

I'd like to know if it's possible to do something similar using scp (instead of ssh + touch). If I try to run:

scp /dev/null remoteserver:~/emptyfile

it returns an error /dev/null: not a regular file

EDIT: Just to clarify, I don't wanna run any command at the remoteserver (i.e. No ssh command should be invoked).

So it's ok to run some command at localhost (echo, cat, dd or any other trivial command) and copy the resulting file to remoteserver.

It's preferable not leaving the resulting file at localhost. It's also good if the resulting command is an one-liner solution.

EDIT2:

It's impossible to use /dev/null approach as in cp command, because scp only works with regular files and directories: https://github.com/openssh/openssh-portable/blob/8a85f5458d1c802471ca899c97f89946f6666e61/scp.c#L838-L850

So it's mandatory to use another command (touch, cat, dd etc) to create a regular empty file (either in a previous command, pipe or a subshell).


Solution

  • As @willh99 commented, creating an empty file locally, and then performing scp is the most feasible solution.

    So far I came up with this:

    filename=$(mktemp) && scp $filename remoteserver:~/emptyfile; rm $filename
    

    It creates an empty file in a subshell, and copies it to remoteserver as emptyfile.

    Any refactor/improvements are welcome.

    EDIT: remove $filename whether scp succeeding or not, as stated by @Friek.