I am trying to use typeset command to execute the function remotely. but unfornately it exit with error.
i have two functions one is for user creation and one that will use to run function remotely
##./create_user -u test1 -g staff -c "test test" -h host1
uadd() {
if grep -E "$username" /etc/passwd >/dev/null; then
echo "$username user already exists in the server $host"
exit 1
else
if grep -E "$groupname" /etc/group >/dev/null; then
/usr/sbin/useradd -G staff,"$groupname" -c "$comment" "$username"
echo "$username user created with staff and $groupname groups!"
exit 1
else
/usr/sbin/useradd -G staff -c "$comment" "$username"
echo "$username user created with staff group only!"
exit 1
fi
fi
}
remoteuadd() {
#ssh sysadm@$host "$(typeset -f useradd); useradd"
ssh root@"$host" -p 5829 "$(declare -f uadd);uadd"
#ssh root@"$host" -p 5829 "$(printf "%q " bash -c "$(declare -f uadd); uadd")"
#typeset -f uadd | ssh -v root@$host -p 5829 `$(cat); `
#ssh root@"$host" -p 5829 bash -s <<EOF
#$(declare -f uadd)
#uadd
#EOF
}
its working but result looks like this
+ remoteuadd
+++ typeset -f uadd
++ uadd '()' '{' egrep '"$username"' /etc/passwd '>' '/dev/null;' if '[' '$?' == 0 '];' then echo '"$username' user already exists in the server '$hostname";' exit '1;' else egrep '$groupname' /etc/group '>' '/dev/null;' if '[' '$?' == 0 '];' then /usr/sbin/useradd -G 'staff,$groupname' -c '"$comment"' '$username;' echo '"$username' user created with '$groupname' 'groups!";' exit '1;' else /usr/sbin/useradd -G staff -c '"$comment"' '$username;' echo '"$username' user created with staff group 'only!";' exit '1;' 'fi;' fi '}'
++ egrep test1 /etc/passwd
++ '[' 0 == 0 ']'
++ echo 'test1 user already exists in the server '
++ exit 1
+ ssh root@localhost -p 5829 test1 user already exists in the server
bash: test1: command not found
+ exit 1
as you can see script try to create user if not exits and so it works and found that user already exits but still script didn't exit it catch the result value and run again and ultimately script break with error.
Any suggestion highly appreciated.
Regards, Mir