bash 在bash中获取进程的用户名和进程ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21728288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the username and the process ID of a process in bash
提问by sat
I am writing a bash script where I need to find out the userID of a process. For an example let the process be bash itself.
我正在编写一个 bash 脚本,我需要在其中找出进程的用户 ID。例如,让进程成为 bash 本身。
I tried ps aux | grep ba[s]h
but the following was returned:
我试过了,ps aux | grep ba[s]h
但返回了以下内容:
1000 2745 0.0 0.1 28360 5440 pts/1 Ss 10:11 0:01 bash
I see the userID 1000 displayed, but I want the username.
我看到显示的用户 ID 1000,但我想要用户名。
回答by sat
This can happen if the username is longer than 8 characters (OR)id has no name. But, If you want the username in the ps
output then try this,
如果用户名超过 8 个字符(OR)id 没有名称,则会发生这种情况。但是,如果你想要ps
输出中的用户名,那么试试这个,
ps -eo uname:20,pid,pcpu,pmem,sz,tty,stat,time,cmd | grep '[b]ash'
回答by Sasha Pachev
You can parse out the /proc
entry if you are on Linux and if you just need a numeric pid (or are OK with it). Here is an example for the mysqld
process:
/proc
如果您使用的是 Linux 并且您只需要一个数字 pid(或者可以接受),则可以解析该条目。以下是该mysqld
过程的示例:
grep -e '^Uid:' /proc/$(pidof mysqld)/status | cut -f 2
回答by EdgeTekSystem
Here is an example for gedit process
这是 gedit 过程的示例
grep -w Pid /proc/$(pidof gedit)/status | cut -f 2
回答by dess
The shortest way I found so far ( $PID - ID of the process inspected):
到目前为止我发现的最短方法( $PID - 检查的进程的 ID):
ps -p $PID -o euid=