refactor: Improve script maintainability and readability with cleaner functions

This commit is contained in:
AbelAnaya 2023-11-14 23:16:55 +01:00
parent 31c8af3446
commit ad59ebcf3a

View file

@ -16,40 +16,44 @@ parse_ssh_port() {
echo $port echo $port
} }
search_ssh_user() { parse_ssh_config() {
for ssh_config in `awk ' for ssh_config in `awk '
$2 == "Host" { $1 == "Host" {
gsub("\\\\.", "\\\\.", $3); gsub("\\\\.", "\\\\.", $2);
gsub("\\\\*", ".*", $3); gsub("\\\\*", ".*", $2);
host = $3; host = $2;
next; next;
} }
$2 == "User" { $1 == "User" {
$2 = ""; $1 = "";
sub( /^[[:space:]]*/, "" ); sub( /^[[:space:]]*/, "" );
printf "%s|%s\n", host, $0; printf "%s|%s\n", host, $0;
}' $1`; do }' $1`; do
local host_regex=${ssh_config%|*} local host_regex=${ssh_config%|*}
local host_user=${ssh_config#*|} local host_user=${ssh_config#*|}
if [[ "$2" =~ $host_regex ]]; then if [[ "$2" == $host_regex ]]; then
ssh_user=$host_user ssh_user_found=$host_user
break break
fi fi
done done
echo $ssh_user echo $ssh_user_found
} }
get_ssh_user() { get_ssh_user() {
# Set default ssh_user as current user # Search SSH User in user local file if available
local ssh_user=$(whoami)
# Search SSH User information in global configuration file
ssh_user=$(search_ssh_user /etc/ssh/ssh_config $1)
if [ -f ~/.ssh/config ]; then if [ -f ~/.ssh/config ]; then
# Search SSH User information in user configuration file ssh_user=$(parse_ssh_config ~/.ssh/config $1)
ssh_user=$(search_ssh_user ~/.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 fi
echo $ssh_user echo $ssh_user