0

I'm no Bash expert and I'm puzzled why my code won't work.

With

od = `pip list --outdated | cut -d ' ' -f 1`; if [ ${#od} -eq 0 ]; then echo 'Up to date'; else echo 'Outdated stuff!'; echo pip install -U $od; fi

I get

od: =: No such file or directory
od: =: Bad file descriptor
-bash: 0: command not found
-bash: [: -neq: unary operator expected

What am I doing wrong here when I try to set the output of test for a list of the names of out of date packages to a variable?

orome
  • 45,163
  • 57
  • 202
  • 418

2 Answers2

1

Don't put space around the = operator in assignments.

od=`pip list --outdated | cut -d ' ' -f 1`; if [ ${#od} -eq 0 ]; then echo 'Up to date'; else echo 'Outdated stuff!'; echo pip install -U $od; fi

Also, don't use back ticks, wrap sub shells in $(...) instead:

od=$(pip list --outdated | cut -d ' ' -f 1); if [ ${#od} -eq 0 ]; then echo 'Up to date'; else echo 'Outdated stuff!'; echo pip install -U $od; fi

Finally, a simpler way of checking if the value of od is empty:

if [ ! "$od" ]; then ...

So that gives:

od=$(pip list --outdated | cut -d ' ' -f 1); if [ ! "$od" ]; then echo 'Up to date'; else echo 'Outdated stuff!'; echo pip install -U $od; fi
janos
  • 120,954
  • 29
  • 226
  • 236
  • Looks good. I might use `read -a` or similar to actually use an array rather than counting on string-splitting to do the right thing, but there's an argument to be made that that's quibbling over corner cases (like non-default IFS values) that aren't particularly likely. – Charles Duffy Nov 02 '15 at 17:39
  • Heh. I'm actually not a fan of using the implicit `-n` argument to test, simply because there's a chance of the data being tested looking like test command syntax. Granted, the really nasty cases of that only come in when using `-a` or `-o` (hence their being deprecated in the current POSIX standard), and the worst one can really get in two-argument usage like this is a harmless error going to stderr and a correct (falsey) exit status, but... *shrug*. – Charles Duffy Nov 02 '15 at 17:41
0
od=`pip list --outdated | cut -d ' ' -f 1`; if [ ${#od} -eq 0 ]; then echo 'Up to date'; else echo 'Outdated stuff!'; echo pip install -U $od; fi

Get rid of the spaces around the =

jayant
  • 2,349
  • 1
  • 19
  • 27