0

I have three if conditions in a shell script I have been given, can I be assisted with what they each mean in English. Also, how would I use the man pages to find out similar commands in the future?

The conditions are as follows:

  1. if [ -z $1 ]

  2. if [ ! -r $1 ]

  3. if [ -n $3 ]

thecartesianman
  • 745
  • 1
  • 6
  • 15
  • 1
    Just checked, everything is in `bash(1)`, see https://linux.die.net/man/1/bash – gstukelj Oct 29 '19 at 17:36
  • 1
    Every command listed in this question is buggy, btw. Needs to be quoted as in `[ -z "$1" ]` to actually behave the way you expect it to. Otherwise, with an empty string, instead of being `[ -z "" ]`, it becomes `[ -n "-z" ]` (because `-n` is the default test in the single-argument case) -- it's still true, but it's true for a different reason than what you expect and intend; and there are other, odder corner cases when the quoting is missing as well. – Charles Duffy Oct 29 '19 at 17:41
  • 1
    ...similarly, `[ -n $3 ]` becomes `[ -n ]`, which is treated as `[ -n "-n" ]`, when `$3` is empty; *unless* you quote it as `[ -n "$3" ]`, in which case it actually does the right thing. – Charles Duffy Oct 29 '19 at 17:44
  • @gst what section in bash(1), I didn't see it in options and document is very long? – thecartesianman Oct 29 '19 at 18:08
  • 1
    @thecartesianman did you try searching on the website? See Conditional Expressions – gstukelj Oct 29 '19 at 18:11

2 Answers2

2

The trick here is that [ is not punctuation, but the name of a command, which is also called test. So the help page you need is man test.

On that page, you can see the options listed:

   -z STRING
          the length of STRING is zero

   ! EXPRESSION
          EXPRESSION is false

   -r FILE
          FILE exists and read permission is granted

   -n STRING
          the length of STRING is nonzero

Since bash includes a built-in implementation of this command, you can also find the information under man bash and in the bash reference manual.

IMSoP
  • 89,526
  • 13
  • 117
  • 169
1

See "CONDITIONAL EXPRESSIONS" in man bash:

-r file
          True if file exists and is readable.

-n string
          True if the length of string is non-zero.   

-z string
          True if the length of string is zero.

Interestingly, ! is not documented in the context of [ ... ], but it means negation in the same way as in other contexts. You can find the explanation in help test or in man bash under SHELL BUILTIN COMMANDS, section [ expr ].

choroba
  • 231,213
  • 25
  • 204
  • 289