1

I have a bash script which runs some jobs. Sometimes I want to be able to run those jobs with nice to lower their priority on a server.

For example, if my executable is a.out, I can run from the terminal nice a.out to lower the job priority.

In my bash script I have a variable NICE. I do one of the following 2 things:

# either nice is set
NICE="nice"

# or it is left unset
NICE=""

I then run my job using

"$NICE$ ./a.out

later in the script.

This works when NICE="nice" however does not work when NICE is left set to NICE="".

One way around this is to use an if statement:

if [ "$NICE" == "nice" ]
then
    nice ./a.out
else
    ./a.out
fi

But this becomes 5 or 6 lines of code rather than just a single line.

Is it possible to accomplish what I was attempting using NICE as a variable to launch an executable with niceness or no niceness?

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225

1 Answers1

2

Your first guess is almost right.

From the Bash man page (emphasis mine):

Explicit null arguments ("" or '') are retained and passed to commands as empty strings. Unquoted implicit null arguments, resulting from the expansion of parameters that have no values, are removed. If a parameter with no value is expanded within double quotes, a null argument results and is retained and passed to a command as an empty string. When a quoted null argument appears as part of a word whose expansion is non-null, the null argument is removed. That is, the word -d'' becomes -d after word splitting and null argument removal.

So for your case, you could simply drop the quotes:

$NICE ./a.out

which, depending on the value of $NICE, will expand to the following two-word command:

'nice' './a.out'

or a one-word command:

'./a.out'

You can use set -x to help debug this kind of expansion -- it prints the expanded word list so you can see if something has gone amiss.

RJHunter
  • 2,829
  • 3
  • 25
  • 30