cat ~/.ssh/id_rsa.pub | ssh [email protected] "mkdir -p ~/.ssh && cat >>  ~/.ssh/authorized_keys"

can someone explain how the quotations works.

From what I understand. I am reading the public key on my disk then piping it to the server, making a directory if it doesn't exist and then... am I using this second concatenation to read from my disk? what is being concatenated?

It get confusing because im used to seeing a file after the cat command.


1 Answer 1


The command cat is able to concatenate files and to print them on the standard output.
When it is invoked without specifying any file or with a -, it will read the standard input.
In your command it is used in both the ways.

Step by step:

  • The first part of your command (cat ~/.ssh/id_rsa.pub) does exactly what you understood: it prints the local file ~/.ssh/id_rsa.pub to the standard output.
  • Then with the symbol | you redirect the local standard output as standard input to the following command (ssh).
  • The ssh command practically will make execute the command inside the string "" on the remote machine passing the standard input from the pipe.
  • Inside the string:
    • You will create the directory ~/.ssh and thanks to the option -p it will not generate error if the directory just exists.
    • With the operator && you will execute the following cat only if the previous mkdir exits without errors.
    • The last cat >> ~/.ssh/authorized_keys is an invocation of cat without file. Its output will be appended (if possible) to the file ~/.ssh/authorized_keys thanks to the redirection operator (>>).


  • On many systems it exists the command ssh-copy-id to copy the local keys on the remote machine. For more info type man ssh-copy-id

    ssh-copy-id — use locally available keys to authorise logins on a remote machine

  • As stated by roalma in the comment the original command line can work or not depending of (restrictive) settings of ssh configuration.

You must log in to answer this question.