How I can print an output number for a running file - linux

How I can get an output message which is "1" or "0" of an already running file?
I mean if i have a .jar file and i tun it by this command java -jar [FILENAME].jar, how i can output a status number( 0 if it is not running or 1 if is running)
N.B: I only want the number as an output message. In a bash script as variable.

i think you are expecting something like this,
[ $(ps -ef | grep "[FILENAME].jar" | grep -v "grep" | wc -l) -gt 0 ] && echo "1" || echo "0"
if need bit more detailed version, then below will suit i guess,
if [ $(ps -ef | grep "[FILENAME].jar" | grep -v "grep" | wc -l) -gt 0 ];then
echo "1"
else
echo "0"
fi

Related

Shell script to kill a process in specific time with process name and time as input

I need a shell script to kill a particular running process after a specific time by getting the process name and time as input.
I'm using centos machine i've tried the script but couldn't complete on killing the process on particular timing.
#!/bin/bash
read -p 'Process: ' name
read -p 'Timecontrol: ' time
ps -ef | grep $name | awk '{print $5}'
pkill -9 "$name"
the expected output to be kill the process in specific time which will be given as input.
With this script you can kill the running process at a specific time by giving the process name and the time.
[Note: The input for time must be in seconds only, i.e 120 for 2 minutes]
#!/bin/bash
LOG=/tmp/kill.log
EXIT_ON_KILL=true
read -p 'Process: ' name
read -p 'killat: ' time
PID=$(ps -ef | grep $name | awk '{print $2}')
ps -ef | grep $name | awk '{print $2}' &>>$LOG
if [ $? -eq 0 ]; then
echo -e "\n The process details "
ps -p $PID
else
echo -e "\nInvalid Process Name"
fi
current=$(date +"%T")
killat=$(date -d "+"$time" seconds" "+%T")
echo -e "\nCurrent time $current \nThe time target is $killat"
while :
do
current=$(date +"%T")
echo $current
if [ "${killat}" == "${current}" ]
then
kill -9 $PID &>>$LOG
if [ $? -eq 0 ]; then
echo "Process $name have been successfully killed"
if [ $EXIT_ON_KILL == true ];then
exit 0
fi
else
echo -e "\nFailed to Kill process $name"
echo -e "\nMay be Invalid Process Name"
exit 1
fi
fi
sleep 2
done
Sample Input:
Process: xxxx
Killat: 120
You can use a cron job to terminate the process in specific date and time.
If you have to use a script:
#!/bin/bash
read -p 'Process: ' name
read -p 'Timecontrol: ' timecontrol
while :
do
now="$(date --date="$(date +%H:%M)" +%s)"
x="$(date --date="$timecontrol" +%s)"
if [ $now == $x ]
then
ps -ef | grep $name | awk '{print $5}'
fi
done
Note:
Remove # if you plan to run this script forever.
The script will not kill the process at that particular time which you want to give it as an input as the script will run and die it will not wait for a specific time.
You can tickle this in two ways.
Loop but again it will run in the foreground
Cronjob
#!/bin/bash
EXIT_ON_KILL=true
read -p 'Process: ' name
read -p 'Timecontrol: ' timecontrol
while :
do
current_time=$(date +"%T")
echo $current_time "control "
current_time=$(echo $current_time | cut -d':' -f1-2)
if [ "${timecontrol}" == "${current_time}" ]
then
echo "killing process"
kill -9 $(ps -ef | grep $name | awk '{print $2}')
if [ $? -eq 0 ]; then
echo "Process killed having name $name and having $pid"
if [ $EXIT_ON_KILL == true ];then
exit 0
fi
else
echo "Failed to Kill process having name $name"
exit 1
fi
fi
sleep 2
done
awk '{print $2}' this return PID in ubuntu, you have to check-in Centos if it returns PID if not then change it to awk '{print $5}'
So you can run with
./kill_process.sh
Process: node
Timecontrol: 00:21
With Cron job, you do not need to pass time, just pass the name of the process and the script will run on the specified time and will kill the process.
#!/bin/bash
EXIT_ON_KILL=true
p_name=$1
kill -9 $(ps -ef | grep $p_name | awk '{print $2}')
if [ $? -eq 0 ]; then
echo "Process killed having name $p_name and having $pid"
if [ $EXIT_ON_KILL == true ];then
exit 0
fi
else
echo "Failed to Kill process having name $p_name"
exit 1
fi
Create-cron-job-on-CentOS
0 0 * * * /path_to_script/kill_process.sh node
This will kill process every-day-at-midnight

What's the actual value of an if-statement executing a command?

I do not quite understand what the following if-statement actually does, in the sense of what the condition outputs could possibly be:
if linux-command-1 | linux-command-2 | linux-command-3 > /dev/null
I understand the execution as the following:
Linux Command 1 gets executed, it's output is PIPED into Linux-Command-2 as input.
Linux Command 2 gets executed with LC1's input, it's output is PIPED into Linux-Command-3.
Linux Command 3 gets executed with LC2's input, it's output is redirected into /dev/null, basically doesn't appear.
But what about the actual if-statement? What's responsible for it becoming true or false?
To further elaborate, here's an example with actual commands:
if ps ax | grep -v grep | grep terminator > /dev/null
then
echo "Success"
else
echo "Fail"
fi
I do know that the functionality behaves in the way that if any output occurs (Process is running) in that execution the condition is True, if nothing occurs (Process not running), the condition is False.
But I don't understand why or how it's coming to that conclusion? Is the shell if statement always expecting a string output as True?
I've also just discovered pgrep but the question would also remain if the statement were
if pgreg -f terminator > /dev/null
In your case you are testing the exit status of grep itself, which will return false (1) if there was no match and true (0) if there was one
if ps ax | grep -v grep | grep terminator > /dev/null
then
echo "Success"
else
echo "Fail"
fi
you could put a "-q" instead of redirection to /dev/null
if ps ax | grep -v grep | grep -q terminator
then
echo "Success"
else
echo "Fail"
fi
I would execute my commad and test the $?
ps ax | grep -v grep | grep terminator
if [ $? -eq 0 ]; then
echo 'it is ok'
else
echo 'is is ko'
fi
If you do:
if linux-command-1 | linux-command-2 | linux-command-3 > /dev/null
only the result of the last command matter
if everything is important put "&&" instead
if ps -ae | grep 'bash' | grep 'pty0' && ls . >/dev/null; then
echo "bash is in the house"
fi
that will fail because there is no not_exist
if ps -ae | grep 'bash' | grep 'pty0' && ls not_exist >/dev/null; then
echo "bash is in the house"
fi

Accessing export variable on remote server

Below is not working when I am trying to access exported variable on remote server under if loop:
VAR=`grep pattern ./checklist | cut -f7`
echo "Port number to be checked for service is $VAR" #working fine
export VAR
ssh -tTq user#node <<EOF
echo "checking service on \`hostname\`";
echo "export value received is $VAR"
echo \$(ps -ef | grep -v grep | grep port=$VAR | wc -l)
if [ \$(ps -ef | grep -v grep | grep port=$VAR | wc -l) == 0 ];
then
echo "service is DOWN"
elif [ \$(ps -ef | grep -v grep | grep port=\$VAR | wc -l) == 1 ];
then
echo "Service is Up"
else
echo "Multiple instances running of selected service"
fi
EOF
Output received of if loop is not as expected:
Multiple instances running of selected service
+ '[' 1 == 2 ']'
instead of 1 == 1 condition match
Found the answer by myself.
In the above question I have missed \ before $VAR by mistake in elif condition.
LL: Strong/single quotes ' should be avoided for the cmds to be executed on remote host when using export variables via ssh.
Avoid using \ on under while calling export variable present between << EOF ..... EOF. (In above example $VAR)

shell script error when declaring command

Code below is supposed to check the memory for user and if its greater than 1000, print message
I keep getting error- line 4: impala: command not found
#!/bin/bash
while [ true ] ;do
used= `ps hax -o rss,user | awk '{a[$2]+=$1;}END{for(i in a)print i"
"int(a[i]/1024+0.5);}' | grep user`
if [[ $used > 1000 ]]; then
echo "user memory is $used"
fi
sleep 5
done
I have tried used= ps hax -o rss,user | awk '{a[$2]+=$1;}END{for(i in a)print i" "int(a[i]/1024+0.5);} | grep user'
and used= 'ps hax -o rss,user | awk '{a[$2]+=$1;}END{for(i in a)print i" "int(a[i]/1024+0.5);}' | grep user'
I need a fresh eye on this. Please help.
In bash, as mentioned [ here ], putting spaces around the equal sign would cause errors, So the right format is
variable_name=value;
Moreover, you may change
while [ true ]
to
while true
Edit
If used has the form impala 600 and you're only interested in the number at the end, then you may do
used="${used##* }"
#Do this just after the your first command.
Finally do
#use -gt for integer comparisons and > for string comparisons
if ! [ -t $used ] && [ $used -gt 1000 ]
then
echo "user memory is $used"
fi
Note: Though the syntax errors in the script is resolved there is no guarantee that the program logic is right

IF statement inside a loop in linux terminal not working

Currently I am trying to execute a bash file in a crontab. However, the command by itself is not working, this is the command.
for ip in $(seq 3 80); do for ip2 in $(seq 9 254); do count=$(ping -c 1 192.168.$ip.$ip2 | grep icmp* | wc -l) if [ $count -eq 0 ]; then echo "Host unreachable" else php /var/www/phpfile.php 192.168.$ip.$ip2 > 192.168.$ip.$ip2.txt; done; done
The error that the console is showing when I execute this command is this:
if: Command not found
I already checked the spaces between the brackets, I also tried to remove them, but none of those solutions have worked. Can you please tell me what is wrong with my command? What am I missing?
Thank you so much in advance.
You are missing a fi and some ;, Try this:
for ip in $(seq 3 80); do for ip2 in $(seq 9 254); do count=$(ping -c 1 192.168.$ip.$ip2 | grep icmp* | wc -l); if [ $count -eq 0 ]; then echo "Host unreachable"; else php /var/www/phpfile.php 192.168.$ip.$ip2 > 192.168.$ip.$ip2.txt;fi; done; done
It's better (for readability) to break codes into multiple lines insead of putting them all in a single line:
for ip in $(seq 3 80); do
for ip2 in $(seq 9 254); do
count=$(ping -c 1 192.168.$ip.$ip2 | grep icmp* | wc -l)
if [ $count -eq 0 ]; then
echo "Host unreachable"
else php /var/www/phpfile.php 192.168.$ip.$ip2 > 192.168.$ip.$ip2.txt;
fi
done
done
At the moment, your "one-line" script is totally unreadable, so it's no surprise that it contains errors. Change it to this:
#!/bin/sh
for ip in $(seq 3 80); do
for ip2 in $(seq 9 254); do
dest="192.168.$ip.$ip2"
if ping -c 1 "$dest" | grep -q 'icmp*'; then
php /var/www/phpfile.php "$dest" > "$dest".txt
else
echo "Host unreachable"
fi
done
done
and call it from your crontab.
I have removed the useless use of grep | wc -l, in place of using grep -q, which returns success if the pattern is matched.
Just since no one else seemed to comment on this.
The reason you got if: Command not found as an error is that the body of your inner loop:
count=$(ping -c 1 192.168.$ip.$ip2 | grep icmp* | wc -l) if [ $count -eq 0 ]; then echo "Host unreachable" else php /var/www/phpfile.php 192.168.$ip.$ip2 > 192.168.$ip.$ip2.txt
was being seen by the shell as a single command and not two commands.
Specifically it was being see as (cleaned up to make it more obvious):
count=$(command) if arg1 arg2 arg3 > outfile
Which then made if the command name (and count a variable set in the environment for that if command) and not, as you expected, a shell keyword akin to how this works:
$ printenv | grep FOO
$ FOO=bar printenv | grep FOO
FOO=bar

Resources