-1

Can someone please tell me what I'm doing wrong here. With this conditionals, I do not expect the block in braces to run if the variable is not set. So why do I keep getting "[: -gt: unary operator expected"?

Thanks

[ -n $start_step_i ] && { 
[ $start_step_i -gt 0 ] && [ $start_step_i -le 4] && start_step=$start_step_i ; 
} 

[ $start_step == 1 ] && echo "Running all steps"
  • [ShellCheck](https://www.shellcheck.net/) points out several problems, including that [you need to quote the parameter](https://github.com/koalaman/shellcheck/wiki/SC2070) in `[ -n "$start_step_i" ]` – that other guy Aug 13 '21 at 20:31

1 Answers1

1

start_step_i is empty.

"But I checked if it was non-empty and the check passed!"

No, you didn't. You failed to quote the parameter expansion, so the empty string was removed from the command as part of word-splitting, and you ran [ -n ], which is interpreted as a test of the literal string -n. Since -n is non-empty, the check succeeds.

Always quote parameter expansions:

[ -n "$start_step_i" ] && 
  [ "$start_step_i" -gt 0 ] &&
  [ "$start_step_i" -le 4] &&
  start_step="$start_step_i"

[ "$start_step" = 1 ] && echo "Running all steps"

One exception: the right-hand side of an assignment is not subject to word-splitting or pathname expansion, so quotes can be safely omitted. start_step=$start_step_i would have been OK.

chepner
  • 497,756
  • 71
  • 530
  • 681