From ad59ebcf3a40e23d81b52057590d0273c2a5bbd6 Mon Sep 17 00:00:00 2001 From: AbelAnaya Date: Tue, 14 Nov 2023 23:16:55 +0100 Subject: [PATCH] refactor: Improve script maintainability and readability with cleaner functions --- scripts/ssh_session.sh | 40 ++++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/scripts/ssh_session.sh b/scripts/ssh_session.sh index b6593ae..acc3614 100755 --- a/scripts/ssh_session.sh +++ b/scripts/ssh_session.sh @@ -16,40 +16,44 @@ parse_ssh_port() { echo $port } -search_ssh_user() { +parse_ssh_config() { for ssh_config in `awk ' - $2 == "Host" { - gsub("\\\\.", "\\\\.", $3); - gsub("\\\\*", ".*", $3); - host = $3; + $1 == "Host" { + gsub("\\\\.", "\\\\.", $2); + gsub("\\\\*", ".*", $2); + host = $2; next; } - $2 == "User" { - $2 = ""; + $1 == "User" { + $1 = ""; sub( /^[[:space:]]*/, "" ); printf "%s|%s\n", host, $0; }' $1`; do local host_regex=${ssh_config%|*} local host_user=${ssh_config#*|} - if [[ "$2" =~ $host_regex ]]; then - ssh_user=$host_user + if [[ "$2" == $host_regex ]]; then + ssh_user_found=$host_user break fi done - echo $ssh_user + echo $ssh_user_found } get_ssh_user() { - # Set default ssh_user as current user - local ssh_user=$(whoami) - - # Search SSH User information in global configuration file - ssh_user=$(search_ssh_user /etc/ssh/ssh_config $1) - + # Search SSH User in user local file if available if [ -f ~/.ssh/config ]; then - # Search SSH User information in user configuration file - ssh_user=$(search_ssh_user ~/.ssh/config $1) + ssh_user=$(parse_ssh_config ~/.ssh/config $1) + fi + + # If SSH User not found, search in global config file + if [ -z $ssh_user ]; then + ssh_user=$(parse_ssh_config /etc/ssh/ssh_config $1) + fi + + #If SSH User not found in any config file, return current user + if [ -z $ssh_user ]; then + ssh_user=$(whoami) fi echo $ssh_user