0

I want to add an ssh-key generated in a shell script to my gcp project metadata. The problem is, that I don't really know how to format the generated key to be in the format which is need for the project metadata. The ssh-key I have looks like this:

ssh-rsa AAAAB3.... username

The format that is stated in the documentation is this:

username:ssh-rsa AAAAB3....

Is there a way to reformat the key within my shell script using echo and cat?

My best try is this: echo $USERNAME:$(cat ~/.ssh/id_rsa.pub), but this still leaves the trailing username at the end.

yarvis
  • 69
  • 1
  • 6

1 Answers1

1

Assuming you are using bash, this should do the trick:

# Use the following line to read the key from a file
# KEY_WITH_USERNAME=$(cat ~/.ssh/id_rsa.pub)

KEY_WITH_USERNAME="ssh-rsa AAAAB3.... username"
USERNAME=${KEY_WITH_USERNAME##* }

KEY_WITHOUT_USERNAME=${KEY_WITH_USERNAME%"$USERNAME"}

echo $USERNAME:$KEY_WITHOUT_USERNAME

Outputs:

username:ssh-rsa AAAAB3....

See related questions about how to remove pre- or suffix from a string in Bash and how to split a string and get the final part.

matsu
  • 316
  • 2
  • 6
  • Small followup question: why does echoing this: `echo $USERNAME:$KEY_WITHOUT_USERNAME > ~/.ssh/id_rsa.pub` into a new file not work? It only take the ":". – yarvis Nov 13 '22 at 14:37
  • Nevermind, fixed it. Forgot to rename the variables. – yarvis Nov 13 '22 at 15:02