I'm trying to send the public id_rsa.pub file from my Mac to the ~/.ssh/authorized_keys directory in my home directory at Linux servers so I can then access without logging in each time.

From my Mac Terminal I'm using this command:

cat ~/.ssh/id_rsa.pub | ssh username@remoteserver 'cat >> ~/.ssh/authorized_keys'

This works if the remote ~/.ssh directory already exists, but doesn't otherwise. In that case I have to first login to the remote server, create the .ssh directory, then logout, and then run the above command. After that I can ssh to the remote server without logging in.

I need to do this for a few dozen servers, so I was wondering if there was a way of modifying the above command to create the remote .ssh directory if it wasn't already present.



1 Answer 1


Use ssh-copy-id

In general ssh-copy-id takes care of nonexistent directory or file. Use it if you can; do not reinvent the wheel.

Without ssh-copy-id (for whatever reason)

On the remote side you run commands in a shell. Run more commands. Make sure the extra commands don't consume stdin before cat does (use </dev/null if needed). Here neither cd nor mkdir uses stdin, so this should work:

cat ~/.ssh/id_rsa.pub | ssh username@remoteserver '
   cd ~/ || exit
   mkdir -pm 700 .ssh
   cat >> .ssh/authorized_keys
   chmod 600 .ssh/authorized_keys


  • -p makes mkdir not complain if ./.ssh already exists as a directory.
  • -m 700 sets the right mode from the very beginning.

The code can be improved. My main point is you are not limited to a single cat.

  • I tried cat ~/.ssh/id_rsa.pub | ssh-copy-id username@remoteserver 'cat >> ~/.ssh/authorized_keys' but get an error /usr/bin/ssh-copy-id: ERROR: Too many arguments. Expecting a target hostname. Is my syntax wrong? May 31, 2020 at 1:56
  • I also tried ssh-copy-id -i ~/.ssh/id_rsa.pub user@server and got the error sed: RE error: illegal byte sequence. May 31, 2020 at 2:01
  • 2
    Plain old ssh-copy-id user@server worked. Thanks! May 31, 2020 at 2:06
  • 3
    You can also make this independent of the working directory; mkdir -pm 700 ~/.ssh; cat >> ~/.ssh/authorized_keys; chmod 600 ~/.ssh/authorized_keys.
    – chepner
    May 31, 2020 at 14:44
  • 1
    Also, the permissions on authorized_keys itself don't matter, so just mkdir -pm 700 ~/.ssh && cat >> ~/.ssh/authorized_keys should do.
    – ilkkachu
    May 31, 2020 at 19:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.