0

I wrote the following bash script:

function getqsubnumber {
# Return how many simulations ($qsubnumber) are currently running

qsubnumber=`qstat | grep p00 | wc -l`

return $qsubnumber
}


getqsubnumber
qs=$?

if [ $qs -le $X ]
    then
        echo 'Running one more simulation'
        $cmd # submit one more job to the cluster
else
    echo 'Too many simulations running ... Sleeping for 2 min'
    sleep 120

The idea is that I am submitting jobs on a cluster. If there are more than X jobs running at the same time, I want to wait for 2 minutes.

The code works for X=50 and for X=200. For some unknown reason, it doesn't work for X=400. Any idea why? The script never wait for 2 minutes, it keeps on submitting jobs.

codeforester
  • 39,467
  • 16
  • 112
  • 140
aloha
  • 4,554
  • 6
  • 32
  • 40

1 Answers1

7

Return values of Unix processes (and a shell function acts like one) can be only in the range of a single byte, i. e. 0…255 (in some contexts the range is -128…+127).

To return values in larger ranges I propose to use the stdout as a channel to provide the result:

function getqsubnumber {
  # Return how many simulations ($qsubnumber) are currently running
  qstat | grep p00 | wc -l
}

qs=$(getqsubnumber)
Alfe
  • 56,346
  • 20
  • 107
  • 159
  • why note use `echo` as what is suggested in @Benjamin's link? – aloha Mar 02 '17 at 23:19
  • 1
    `echo` writes something to stdout. So do many other programs, e. g. `wc`. You can capture the output of `wc` (`x=$(… | wc -l)`) and then print it again to stdout using `echo` (`echo "$x"`). But the result will be the same as if you hadn't captured it and instead had allowed it to be written to stdout in the first place ;-) – Alfe Mar 02 '17 at 23:22
  • one more question since I am new to coding in bash, what are the parenthesis for? Does `qs=$getqsubnumber` work? (I just reran my script, so I cannot test it now!) – aloha Mar 02 '17 at 23:36
  • The dollar-parentheses operator is the modern variant of the backquotes (which are discouraged by now), so they are replaced by the output of the command within the parentheses. `qs=$getqsubnumber` would try to find a _variable_ named `getqsubnumber` and would be replaced by the variable's value (but there isn't one in this context, so it would result in setting `qs` to an empty string). – Alfe Mar 03 '17 at 00:35
  • 1
    These are basic FAQs. See [useless use of backticks](http://www.iki.fi/era/unix/award.html#backticks) and "useless use of `echo`" on the same page, and http://stackoverflow.com/questions/4651437/how-to-set-a-variable-to-the-output-from-a-command-in-bash ... More generally, you (the OP) might want to check out the [Stack Overflow `bash` tag wiki](/tags/bash/info) for these basic questions. – tripleee Mar 03 '17 at 04:51
  • (Looking up such links is always more work for me than simply answering the questions at hand, but the links are probably more useful in the long run.) – Alfe Mar 03 '17 at 10:00