I'd like to extract a setting for a given host in the ssh_config file and put it into a variable.

Host mysite
    User myuser
    Port 13245
    GSSAPIAuthentication no
    IdentityFile /home/myuser/.ssh/id_dsa

Host anothersite
    HostName 321.2.2.2
    User myuser
    Port 22
    GSSAPIAuthentication no
    IdentityFile /home/myuser/.ssh/anothersite_dsa

I need to match the first occurrence of the value for the given setting after the host name has been matched first. I've just begun to learn basic regex and this is as far as I've gotten on my own, but I've got too much time into this and could use some help. The script finds the first occurrence of "IdentityFile" after it matches "Host mysite" and replace the word "IdentityFile" with "test".

get_host_option() {
    [ -f /etc/ssh/ssh_config ] || return
    perl -0pe 's/(?<=Host[[:space:]]'"$HOST"')(.*?)'"$option"'/$1test/s' /etc/ssh/ssh_config
get_host_option "$IDS"

What I need is the path that has been set for IdentityFile to be placed into a variable. So that I could us it like this.

ssh-add $IDPATH

1 Answer 1


Try this :

perl -0ne 'print $& if /^Host.*?IdentityFile\s+\K[^\n]+/ms' file

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.