Inline if shell script

后端 未结 5 1883
一向
一向 2021-02-02 06:12

Is it possible to execute shell script in command line like this :

counter=`ps -ef | grep -c \"myApplication\"`; if [ $counter -eq 1 ] then; echo \"true\";
>
         


        
相关标签:
5条回答
  • 2021-02-02 06:13

    Yes, with syntax issues fixed

    That almost worked. The correct syntax is:

    counter=`ps -ef | grep -c "myApplication"`; if [ $counter -eq 1 ]; then echo "true"; fi
    

    But note that in an expression of this sort involving ps and grep, the grep will usually match itself because the characters "grep -c Myapplication" show up in the ps listing. There are several ways around that, one of them is to grep for something like [M]yapplication.

    0 讨论(0)
  • 2021-02-02 06:15

    Other responses have addressed your syntax error, but I would strongly suggest you change the line to:

    test $(ps -ef | grep -c myApplication) -eq 1 && echo true
    

    If you are not trying to limit the number of occurrences to exactly 1 (eg, if you are merely trying to check for the output line myApplication and you expect it never to appear more than once) then just do:

    ps -ef | grep myApplication > /dev/null && echo true
    

    (If you need the variable counter set for later processing, neither of these solutions will be appropriate.)

    Using short circuited && and || operators is often much clearer than embedding if/then constructs, especially in one-liners.

    0 讨论(0)
  • 2021-02-02 06:28

    I am using Mac OS and following worked very well

    $ counter=`ps -ef | grep -c "myApplication"`; if [ $counter -eq 1 ]; then echo "true";fi;
    

    true

    Space is needed after [ and before ]

    0 讨论(0)
  • 2021-02-02 06:31

    I was struggling to combine both multiple lines feed into command and getting its results into a variable (not a file) and come up with this solution:

        FRA_PARAM="'db_recovery_file_dest'"
        FRA=$(
        sqlplus -S "/as sysdba" <<EOF
    set echo off head off feed off newpage none pages 1000 lines 1000
    select value from v\$parameter where name=$FRA_PARAM;
    exit;
    EOF
            )
    

    Please note that single-quotes word was substituted, because otherwise I was receiving its autosubstitution to double quotes... ksh, HP-UX.

    Hopefully this will be helpful for somebody else too.

    0 讨论(0)
  • 2021-02-02 06:32

    It doesn't work because you missed out fi to end your if statement.

    counter=`ps -ef | grep -c "myApplication"`; if [ $counter -eq 1 ]; then echo "true"; fi
    

    You can shorten it further using:

    if [ $(ps -ef | grep -c "myApplication") -eq 1 ]; then echo "true"; fi
    

    Also, do take note the issue of ps -ef | grep ... matching itself as mentioned in @DigitalRoss' answer.

    update

    In fact, you can do one better by using pgrep:

    if [ $(pgrep -c "myApplication") -eq 1 ]; then echo "true"; fi
    
    0 讨论(0)
提交回复
热议问题