1

I'm new to bash scripting and I'm trying to learn one of the scripts my company uses. I came across this line:

[ ! -f $PKGDIR/$COMMON_OPS_SCRIPT ] && exit $MISSING_COMMONOPS_SCRIPT

the next line is:

. $PKGDIR/$COMMON_OPS_SCRIPT

The first line confuses me because it looks like it should be part of an if statement but it isn't. The second line is the same thing in the brackets on the first line preceded by a period. Can someone please explain, in detail, what is happening here?

Also, I've been trying to learn bash scripting here:

https://ryanstutorials.net/bash-scripting-tutorial/

Does anyone have a better tutorial I could check out?

3

You do not need an if because of the && that can be used equivalent.

[ ] : conditional test
! not
-f FILE : does FILE exist ?
&& : do the following only if the statement before is true (returns 0)
exit : exit the script
. FILE : include FILE

So the script checks if the file does not exist and exits the script when that is true. Otherwise it will source/include that file.


These 3 are equivalent:

if [ something ]; then something_else; fi

[ something] && something_else

test something && something_else
4
  • The latter two are not entirely equivalent to the if example. In those two cases, something_different will be executed if something_else exits with non-zero code. This doesn't happen for the if else example – user000001 Aug 29 '17 at 14:31
  • true, I missed that... – pLumo Aug 29 '17 at 14:33
  • I know $ means "value of" so does $PKGDIR/$COMMON_OPS_SCRIPT return a value? If $PKGDIR is 1 and $COMMON_OPS_SCRIPT is 0 (division by 0) does that throw some kind of error? Or am I looking at this completely wrong? And what about the second line? . FILE includes a file but $PKGDIR/$COMMON_OPS_SCRIPT looks like a value not a file. – Bishop Minter Aug 29 '17 at 14:45
  • $var is a variable. -f $var checks if $var is a file – pLumo Aug 29 '17 at 14:52
1

that's checking if there is a file in $PKGDIR/$COMMON_OPS_SCRIPT exists, then source it . $PKGDIR/$COMMON_OPS_SCRIPT in next line, otherwise exit and return $MISSING_COMMONOPS_SCRIPT

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.