3

how can I get status from command, which is assigned into variable?

For example:

#! /bin/bash

### GET PID
GETPID=$(ps aux | grep "bash" | grep -v "grep" | awk '{print $2 }')

if [ "$?" = "0" ]; then
    echo "status OK"
else 
    echo "status NOT OK"
fi
peterko
  • 503
  • 1
  • 6
  • 18
  • If you want to get your current process id, you can use `$$` --> `echo $$`. Regarding the question itself, your `if` condition checks an integer, so that you want to say `if [ "$?" -eq 0 ]"`... that is, use `-eq` to check equality in integers. – fedorqui Jun 23 '15 at 15:25
  • I don't understand the question here...do you want the output of the command, or the exit status, or both (or what)? – Tom Fenech Jun 23 '15 at 15:30
  • @fedorqui - Thanks for the comments relating to the comparison integer. But i also need in my script check if any command return bad status or no (for example somebody who run script are not allowed run other script...). – peterko Jun 23 '15 at 15:34
  • @TomFenech - I want the output of the command and the exit status (both) – peterko Jun 23 '15 at 15:35
  • 1
    You already have them in that case - the output is in `$GETPID` and the exit status is in `$?`. What's the problem? – Tom Fenech Jun 23 '15 at 15:37
  • Just in passing - if you have `pgrep`, you can replace that pipeline with something shorter and more reliable. – Toby Speight Jun 23 '15 at 16:06
  • take a look here http://stackoverflow.com/questions/9277827/getting-exit-code-from-subshell-through-the-pipes – Yuri G. Jun 23 '15 at 20:13

1 Answers1

2

How about this:

PID=($(pidof bash))
if [[ ${#PID[@]} -gt 0 ]]; then
    echo "status OK"
else
    echo "status not OK"
fi
arco444
  • 22,002
  • 12
  • 63
  • 67
MYMNeo
  • 818
  • 5
  • 9