我的任务是列出两台主机中所有正在运行的mariadb进程,并在最后获得实例名称(实例名称等于正在运行进程的用户),我可以为它编写一个脚本(如下所示)。但在本例中,在某些主机中,username/instance_name等于数字,例如3124855。在本例中,我知道命令getent passwd 3124855 |cut -d':‘-f1可以为我打印正确用户名,而不是数字。问题是如何将此命令放入脚本以始终获得正确的用户名?
#!/bin/sh
result=$(ps -ef|grep "mysqld"|grep -v grep|awk '{print $8}')
if [ -z "${result}" ] ; then
echo "no_instances"
exit 0
else
OIFS=$IFS
IFS=$'\n'
for i in $(ps -ef|grep "mysqld"|grep -v grep); do
if [[ $(`echo $i|awk '{print $8}'` --version) == *"MariaDB"* ]]; then
echo $i|awk '{print $1}'
fi
done
IFS=$OIFS
fi发布于 2017-12-19 17:34:23
您可以强制ps输出数字uid,因此您将始终拥有一个数字用户,然后可以将其转换为用户名。
请参阅ps的手册页。
例如,使用ps -eo ruid、cmd
因此,awk的位置参数将是数字userid的$1和cmd的$2。
发布于 2017-12-19 17:38:39
像这样编辑你的代码:
#!/bin/bash
result=$(ps -ef|grep "mysqld"|grep -v grep|awk '{print $8}')
if [ -z "${result}" ] ; then
echo "no_instances"
exit 0
else
OIFS=$IFS
IFS=$'\n'
for i in $(ps -ef|grep "mysqld"|grep -v grep); do
if [[ $(`echo $i|awk '{print $8}'` --version) == *"MariaDB"* ]]; then
[ -z $(echo "${i}" | awk '{print $1}' | sed -r 's/^[0-9]+$//g') ] && echo $(getent passwd ${i} | cut -d':' -f1) || echo $i|awk '{print $1}'
fi
done
IFS=$OIFS
fiConstriction [ -z $(echo "${i}" | awk '{print $1}' | sed -r 's/^[0-9]+$//g') ]将检查UID是否只有数字。如果为真,将执行代码&& echo $(getent passwd ${i} | cut -d':' -f1)。如果为false,则脚本运行|| echo $i|awk '{print $1}'
https://stackoverflow.com/questions/47883550
复制相似问题