-n option for /bin/test

jrick

Member

Reaction score: 6
Messages: 84

I am trying to convert a simple script that I wrote from zsh to /bin/sh, but it seems that the behavior of the -n option for conditional tests is different from zsh.

Example from zsh:

Code:
if [[ -n `pgrep xmms2d` ]]; then
echo "This code will not be run."
fi
And in sh:

Code:
if [ -n `pgrep xmms2d` ]; then
echo "This code will run."
fi
Can anyone explain this, and a possible work around that I can use?
 

DutchDaemon

Administrator
Staff member
Administrator
Moderator
Developer

Reaction score: 2,816
Messages: 11,305

Are you looking for something like this?

Code:
 if pgrep xmms2d
then
echo "This code will run."
fi
or even

Code:
pgrep xmms2d && echo "This code will run."
pgrep xmms2d || echo "This code will not run."
 
OP
OP
J

jrick

Member

Reaction score: 6
Messages: 84

DutchDaemon said:
Are you looking for something like this?

Code:
 if ! pgrep xmms2d
or even

Code:
pgrep xmms2d || echo "This code will run."
Well, maybe it would be good if I showed the whole script:

Code:
#!/bin/sh

UPDATE=1
SYSTEM=`uname -sr`

while :; do
    DATE=`date +"%a %B %d, %I:%M %p"`
    BATTERY=`sysctl -n hw.acpi.battery.life`
    # if xmms2d is running
    if [ -n `pgrep xmms2d` ]; then
        # another if statement, stopped or not
        if [ `nyxmms2 status | grep -Eo '^Stopped:'` = "Stopped:" ]; then
            XMMS2=" ^fg(green)XMMS2 is stopped^fg() |"
        else
            XMMS2=" ^fg(green)`nyxmms2 status | grep -Eo '^[^:]+:[^:]+'`^fg() |"
        fi  
    else
        XMMS2=""
    fi  
    echo "^fg(red)$SYSTEM^fg() |$XMMS2 ^fg(#00FFFF)$BATTERY%^fg() | ^fg(orange)$DATE^fg() "
    sleep $UPDATE
done | dzen2 -fn '-*-terminus-medium-r-*-*-12-*-*-*-*-*-*-*' -bg '#222222' -fg '#aaaaaa' -w 840 -ta r -x 840
I want to test to see if xmms2d is running, and if it is, then run the rest of that code.

This almost works:

Code:
if ! pgrep xmms2d ; then
  echo "test"
fi
"test" is not echoed at all, but it still prints the pid of xmms2d, which I really don't want.
 

DutchDaemon

Administrator
Staff member
Administrator
Moderator
Developer

Reaction score: 2,816
Messages: 11,305

Code:
if ! pgrep xmms2d > /dev/null 2>&1 ; then
  echo "test"
fi
 
Top