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

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

Related

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)

How I can print an output number for a running file

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

Check if a program in a specific path is running

I am trying to check if a process is running with the code below:
SERVICE="./yowsup/yowsup-cli"
RESULT=`ps aux | grep $SERVICE`
if [ "${RESULT:-null}" = null ]; then
echo "not running"
else
echo "running"
fi
But it keeps echoing it is running although it is not. I realized that the grep itself comes as a result and that is the issue.
How can I skip the grep and just check for the process?
Use pgrep:
if pgrep "$SERVICE" >/dev/null 2>&1 ; then
echo "$SERVICE is running"
fi
or:
if pgrep -f "/path/to/$SERVICE" >/dev/null 2>&1 ; then
echo "$SERVICE is running"
fi
NOTE:
pgrep interprets its argument as a regular expression. As a result, paths containing regex characters will likely fail to match or produce false positives (e.g. pgrep -f /home/user/projects/c++/application/executable won't work as expected due to +). This issue can be worked around by escaping the characters in question (e.g. pgrep -f /home/user/projects/c\+\+/application/executable)
pgrep -f <pattern> matches the specified pattern against the whole command line of running processes. As a result, it will match paths appearing as arguments of other processes (e.g. run nano /usr/bin/sleep in one terminal and pgrep -f /usr/bin/sleep in another -> pgrep reports the pid of nano since it contains /usr/bin/sleep as an argument in its command line). To prevent these kind of false positives, prefix the pattern with a caret (^) to force pgrep to only match against the beginning of the command line (e.g. pgrep -f ^/usr/bin/sleep)
For systems where pgrep isn't available you can use:
service="[.]/yowsup/yowsup-cli"
if ps aux | grep -q "$service"; then
echo "not running"
else
echo "running"
fi
[.] in will force grep to not list itself as it won't match [.] regex.
grep -q can be utilized to avoid command substitution step.
Prefer using lowercase variables in shell.
The problem is that grep you call sometimes finds himself in a ps list, so it is good only when you check it interactively:
$ ps -ef | grep bash
...
myaut 19193 2332 0 17:28 pts/11 00:00:00 /bin/bash
myaut 19853 15963 0 19:10 pts/6 00:00:00 grep --color=auto bash
Easiest way to get it is to use pidof. It accepts both full path and executable name:
service="./yowsup/yowsup-cli" # or service="yowsup-cli"
if pidof "$service" >/dev/null; then
echo "not running"
else
echo "running"
fi
There is more powerful version of pidof -- pgrep.
However, if you start your program from a script, you may save it's PID to a file:
service="./yowsup/yowsup-cli"
pidfile="./yowsup/yowsup-cli.pid"
service &
pid=$!
echo $pid > $pidfile
And then check it with pgrep:
if pgrep -F "$pidfile" >/dev/null; then
echo "not running"
else
echo "running"
fi
This is common technique in /etc/init.d start scripts.
The following solution avoids issues with ps + grep, pgrep and pidof (see Advantages below):
# Check if process is running [$1: path to executable]
function is_process_running() {
local path="$1" line
while read -r line; do
[[ "${line}" == "${path}" || "${line}" == "${path} "* ]] && return 0
done < <(ps -e -o command=)
return 1
}
is_process_running "./yowsup/yowsup-cli" && echo "running" || echo "not running"
Explanation:
ps -e -o command= list all processes, only output command line of each process, omit header line
while read -r line; do ... done < <(ps ...) process output produced by ps line by line
[[ "${line}" == "${path}" || "${line}" == "${path} "* ]] check if line matches path exactly -or- path + space + argument(s)
Advantages:
Works for paths containing regex special characters that would trip grep without option -F or pgrep, e.g. /home/user/projects/c++/application/executable (see NOTE in this answer for details)
Avoids issues with ps + grep / pgrep reporting false positives if path appears as argument of some other process (e.g. nano /usr/bin/sleep + pgrep -f /usr/bin/sleep -> falsely reports pid of nano process)
Avoids issues with pidof reporting false positives for processes that are run from PATH (e.g. sleep 60s & + pidof /tmp/sleep -> falsely reports pid of sleep process running from /usr/bin/sleep, regardless of whether /tmp/sleep actually exists or not)
I thought pidof was made for this.
function isrunning()
{
pidof -s "$1" > /dev/null 2>&1
status=$?
if [[ "$status" -eq 0 ]]; then
echo 1
else
echo 0
fi
)
if [[ $(isrunning bash) -eq 1 ]]; then echo "bash is running"; fi
if [[ $(isrunning foo) -eq 1 ]]; then echo "foo is running"; fi
## bash
## function to check if a process is alive and running:
_isRunning() {
ps -o comm= -C "$1" 2>/dev/null | grep -x "$1" >/dev/null 2>&1
}
## example 1: checking if "gedit" is running
if _isRunning gedit; then
echo "gedit is running"
else
echo "gedit is not running"
fi
## example 2: start lxpanel if it is not there
if ! _isRunning lxpanel; then
lxpanel &
fi
## or
_isRunning lxpanel || (lxpanel &)
Note: pgrep -x lxpanel or pidof lxpanel still reports that lxpanel is running even when it is defunct (zombie); so to get alive-and-running process, we need to use ps and grep
current_pid="$$" # get current pid
# Looking for current pid. Don't save lines either grep or current_pid
isRunning=$(ps -fea | grep -i $current_pid | grep -v -e grep -e $current_pid)
# Check if this script is running
if [[ -n "$isRunning" ]]; then
echo "This script is already running."
fi
SERVICE="./yowsup/yowsup-cli"
RESULT=`ps aux | grep $SERVICE|grep -v grep`
if [ "${RESULT:-null}" = null ]; then
echo "not running"
else
echo "running"
fi

How can I obtain command returning status in linux shell

Say, I call grep "blabla" $file in my shell. How could I know whether grep found "blabla" in $file?
I try ret='grep "blabla" $file', will this work by viewing the value of ret? If yes, is ret integer value or string value or something else?
If you do exactly
ret='grep "blabla" $file'
then ret will contain the string "grep "blabla" $file".
If you do (what you meant)
ret=`grep "blabla" $file`
then ret will contain whatever output grep spit out (the lines that matched "blabla" in $file).
If you just want to know whether grep found any lines that matched "blabla" in $file then you want to check the return code of grep -q blabla "$file" (note that you don't need to quote literal strings when they don't contain special characters and that you should quote variable references).
The variable $? contains the return code of the most recently executed command. So
grep -q blabla "$file"
echo "grep returned: $?"
will echo the return code from grep which will be 0 if any lines were output.
The simplest way to test that and do something about it is, however, not to use $? at all but instead to just embed the grep call in an if statement like this
if grep -q blabla "$file"; then
echo grep found something
else
echo grep found nothing
fi
When you run the command
grep blabla "$file"
Status is saved in the variable $?. 0 is good, greater than 0 is bad. So you
could do
grep -q blabla "$file"
if [ $? = 0 ]
then
echo found
fi
Or save to a variable
grep -q blabla "$file"
ret=$?
if [ $ret = 0 ]
then
echo found
fi
Or just use if with grep directly
if grep -q blabla "$file"
then
echo found
fi

Functionality of a start-stop-restart shell script

I am a shell scripting newbie trying to understand some code, but there are some lines that are too complexe for me. The piece of code I'm talking about can be found here: https://gist.github.com/447191
It's purpose is to start, stop and restart a server. That's pretty standard stuff, so it's worth taking some time to understand it. I commented those lines where I am unsure about the meaning or that I completely don't understand, hoping that somone could give me some explanation.
#!/bin/bash
#
BASE=/tmp
PID=$BASE/app.pid
LOG=$BASE/app.log
ERROR=$BASE/app-error.log
PORT=11211
LISTEN_IP='0.0.0.0'
MEM_SIZE=4
CMD='memcached'
# Does this mean, that the COMMAND variable can adopt different values, depending on
# what is entered as parameter? "memcached" is chosen by default, port, ip address and
# memory size are options, but what is -v?
COMMAND="$CMD -p $PORT -l $LISTEN_IP -m $MEM_SIZE -v"
USR=user
status() {
echo
echo "==== Status"
if [ -f $PID ]
then
echo
echo "Pid file: $( cat $PID ) [$PID]"
echo
# ps -ef: Display uid, pid, parent pid, recent CPU usage, process start time,
# controling tty, elapsed CPU usage, and the associated command of all other processes
# that are owned by other users.
# The rest of this line I don't understand, especially grep -v grep
ps -ef | grep -v grep | grep $( cat $PID )
else
echo
echo "No Pid file"
fi
}
start() {
if [ -f $PID ]
then
echo
echo "Already started. PID: [$( cat $PID )]"
else
echo "==== Start"
# Lock file that indicates that no 2nd instance should be started
touch $PID
# COMMAND is called as background process and ignores SIGHUP signal, writes it's
# output to the LOG file.
if nohup $COMMAND >>$LOG 2>&1 &
# The pid of the last background is saved in the PID file
then echo $! >$PID
echo "Done."
echo "$(date '+%Y-%m-%d %X'): START" >>$LOG
else echo "Error... "
/bin/rm $PID
fi
fi
}
# I don't understand this function :-(
kill_cmd() {
SIGNAL=""; MSG="Killing "
while true
do
LIST=`ps -ef | grep -v grep | grep $CMD | grep -w $USR | awk '{print $2}'`
if [ "$LIST" ]
then
echo; echo "$MSG $LIST" ; echo
echo $LIST | xargs kill $SIGNAL
# Why this sleep command?
sleep 2
SIGNAL="-9" ; MSG="Killing $SIGNAL"
if [ -f $PID ]
then
/bin/rm $PID
fi
else
echo; echo "All killed..." ; echo
break
fi
done
}
stop() {
echo "==== Stop"
if [ -f $PID ]
then
if kill $( cat $PID )
then echo "Done."
echo "$(date '+%Y-%m-%d %X'): STOP" >>$LOG
fi
/bin/rm $PID
kill_cmd
else
echo "No pid file. Already stopped?"
fi
}
case "$1" in
'start')
start
;;
'stop')
stop
;;
'restart')
stop ; echo "Sleeping..."; sleep 1 ;
start
;;
'status')
status
;;
*)
echo
echo "Usage: $0 { start | stop | restart | status }"
echo
exit 1
;;
esac
exit 0
1)
COMMAND="$CMD -p $PORT -l $LISTEN_IP -m $MEM_SIZE -v" — -v in Unix tradition very often is a shortcut for --verbose. All those dollar signs are variable expansion (their text values are inserted into the string assigned to new variable COMMAND).
2)
ps -ef | grep -v grep | grep $( cat $PID ) - it's a pipe: ps redirects its output to grep which outputs to another grep and the end result is printed to the standard output.
grep -v grep means "take all lines that do not contain 'grep'" (grep itself is a process, so you need to exclude it from output of ps). $( $command ) is a way to run command and insert its standard output into this place of script (in this case: cat $PID will show contents of file with name $PID).
3) kill_cmd.
This function is an endless loop trying to kill the LIST of 'memcached' processes' PIDs. First, it tries to send TERM signal (politely asking each process in $LIST to quit, saving its work and shutting down correctly), gives them 2 seconds (sleep 2) to do their shutdown job and then tries to make sure that all processes are killed using signal KILL (-9), which slays the process immediately using OS facilities: if a process has not done its shutdown work in 2 seconds, it's considered hung). If slaying with kill -9 was successful, it removes the PID file and quits the loop.
ps -ef | grep -v grep | grep $CMD | grep -w $USR | awk '{print $2}' prints all PIDs of processes with name $CMD ('memcached') and user $USR ('user'). -w option of grep means 'the Whole word only' (this excludes situations where the sought name is a part of another process name, like 'fakememcached'). awk is a little interpreter most often used to take a word number N from every line of input (you can consider it a selector for a column of a text table). In this case, it prints every second word in ps output lines, that means every PID.
If you have any other questions, I'll add answers below.
Here is an explanation of the pieces of code you do not understand:
1.
# Does this mean, that the COMMAND variable can adopt different values, depending on
# what is entered as parameter? "memcached" is chosen by default, port, ip address and
# memory size are options, but what is -v?
COMMAND="$CMD -p $PORT -l $LISTEN_IP -m $MEM_SIZE -v"
In the man, near -v:
$ man memcached
...
-v Be verbose during the event loop; print out errors and warnings.
...
2.
# ps -ef: Display uid, pid, parent pid, recent CPU usage, process start time,
# controling tty, elapsed CPU usage, and the associated command of all other processes
# that are owned by other users.
# The rest of this line I don't understand, especially grep -v grep
ps -ef | grep -v grep | grep $( cat $PID )
Print all processes details (ps -ef), exclude the line with grep (grep -v grep) (since you are running grep it will display itself in the process list) and filter by the text found in the file named $PID (/tmp/app.pid) (grep $( cat $PID )).
3.
# I don't understand this function :-(
kill_cmd() {
SIGNAL=""; MSG="Killing "
while true
do
## create a list with all the pid numbers filtered by command (memcached) and user ($USR)
LIST=`ps -ef | grep -v grep | grep $CMD | grep -w $USR | awk '{print $2}'`
## if $LIST is not empty... proceed
if [ "$LIST" ]
then
echo; echo "$MSG $LIST" ; echo
## kill all the processes in the $LIST (xargs will get the list from the pipe and put it at the end of the kill command; something like this < kill $SIGNAL $LIST > )
echo $LIST | xargs kill $SIGNAL
# Why this sleep command?
## some processes might take one or two seconds to perish
sleep 2
SIGNAL="-9" ; MSG="Killing $SIGNAL"
## if the file $PID still exists, delete it
if [ -f $PID ]
then
/bin/rm $PID
fi
## if list is empty
else
echo; echo "All killed..." ; echo
## get out of the while loop
break
fi
done
}
This function will kill all the processes related to memcached slowly and painfully (actually quite the opposite).
Above are the explanations.

Resources