简体   繁体   English

Shell脚本命令输出与命令行输出不同

[英]Shell script command output differes from command line output

OS: RHEL 7.3. 操作系统:RHEL 7.3。 I am running below command : 我正在下面的命令运行:

ps uax | grep 'elasticsearch' | grep -v grep | awk '{print $2}'

If I run this command on terminal, I get one PID of Elasticsearch process. 如果在终端上运行此命令,则会得到一个Elasticsearch进程的PID。 However if same command I put inside a shell script like so: 但是,如果我将相同的命令放入一个shell脚本中,例如:

#!/bin/bash

PID=$(ps uax | grep 'elasticsearch' | grep -v grep | awk '{print $2}')
echo $PID

I get several PIDs one below other. 我得到几个PID一个在另一个。 What could be going wrong? 可能出什么问题了?

Full script which launches ES is as follows: 启动ES的完整脚本如下:

#!/bin/bash

if [ "$ES_HOME" == "" ]; then
        echo "ES_HOME environment variable does not exists. Please set it to home dir of Elasticsearch and try again"
fi;

PID=$(ps aux | grep "elasticsearch" | grep -vE "start|grep" | awk '{print $2}' | xargs)
if [ "$PID" != "" ]; then
        echo "Elasticsearch is already running with PID: $PID"
        echo ""
        exit;
fi;

echo "Starting Elasticsearch"
sh $ES_HOME/bin/elasticsearch.sh > /dev/null &

In your script you are running it in bash shell #!/bin/bash , just check what is your current shell when you execute manually. 在脚本中,您正在bash shell #!/bin/bash中运行它,只需在手动执行时检查当前的shell是什么。 If different change the shell accordingly. 如果不同,请相应地更改外壳。 Otherwise I do not see any difference. 否则我看不出任何区别。 Also check what user ID you are using while running the script. 还要检查运行脚本时使用的用户ID。

if pgrep is unavailable on your machine, you can use ps without grep to get only the pid of a process using its name . 如果pgrep在您的计算机上不可用,则可以使用不带grep ps来使用其name仅获取进程的pid

For example, 例如,

 #!/bin/bash

_pid=$(ps -C NetworkManager -o pid=)
echo "$_pid"

NetworkManager is the name of the command that one will see in the process table, when using ps . NetworkManager是使用ps时将在进程表中看到的命令的名称。 You can replace that with elasticsearch . 您可以将其替换为elasticsearch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM