for $! and $? This type of context-dependent variable, when it is pushed to the remote host as part of the command line, be sure to consider its particularity, otherwise the script will be difficult to execute in the way you expect, and the resulting error will be difficult to locate.
Let us two examples:
The first example is to push "create user groups and users" to the remote host via SSH:
AddUser () { node=$1 user=$2 group=$3 ssh-t [email protected] $node <<eof #add Group if not exists egrep "^ $group"/etc/group >&/dev/null if ["$?"! = "0"] then groupadd "$group" Fi #add user if not exists egrep "^ $user"/etc/passwd >&/dev/null if ["$?"! = "0"] then
useradd-g "$group" "$user" fieof}
The problem occurs in:
If ["
$?"!= "0"]
$? Not Egrep "^ $group"/etc/group >&/dev/null Execution Results! It's the result of the previous command that was executed before SSH logged in!
A similar problem occurs in the following script that attempts to obtain the PID of the previous background running process:
ssh-t [email protected]<<eofsu-l hive-c "Nohup $HIVE _home/bin/hive--service metastore-hiveconf Hive.log.file=hi ve-metastore.log-hiveconf hive.log.dir= $HIVE _log_dir> $HIVE _log_dir/hive-metastore.out 2> $HIVE _log_dir/ Hive-metastore.log & "Su-l hive-c" Echo $!| cat> $HIVE _pid_dir/hive-metastore.pid "EOF
The problem here is that echo
$!| Cat> $HIVE _pid_dir/hive-metastore.pid,$! The value is not the PID of the Hive Metastore service on the remote host, but the pid! of the previous backend service on this machine
The simple summary is that if you are going to push commands through SSH to a remote host, you need to be especially careful when you use a command that uses a full-context-dependent variable, which is generally not what you expect!
Shell traps: $! and $? Variables that are evaluated when pushed to the remote host for execution