-2

I have been trying to figure out the following line of code as well: if [ ! -e $1 ] thanks

Markos446
  • 23
  • 1
  • 2
  • 1
    http://explainshell.com/ is your friend. – Charles Duffy Feb 22 '18 at 15:44
  • ...also, we want one distinct and non-duplicative question to a question. If this *weren't* closed as duplicate, it could also be closed as overbroad for asking multiple questions at once. Enforcing these rules helps us build a "long-tail" database with the best possible answers for as many unique questions as possible -- if we have different answers for one "question" that asks both A+B, and a second set of answers for another "question" that asks both A+C, then there's no single canonical place someone with only question A can go for the best possible community-reviewed answer. – Charles Duffy Feb 22 '18 at 15:50

1 Answers1

1

Lets break it down:

  • $# is the number of remaining arguments
  • [ is the test command
  • -ne is the numeric "not equals" operator.

So if [ $# -ne 1 ] is testing if there is exactly one argument (left).

In your second example:

  • ! means not
  • -e tests if a file exists
  • $1 is the first remaining argument

Therefore if [ ! -e $1 ] tests that there is no file or directory whose path is given as the first (remaining) argument.

Note that this may fail if the argument is a pathname containing whitespace or globing meta-characters. Quoting is needed to stop word splitting and globbing potentially mangling the pathname; i.e. if [ ! -e "$1" ]

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • `in "$@"` would be more accurate than `in $*`, as `$*` string-splits and glob expands (changing an argument list of `"first argument" "second argument"` (syntactic vs literal quoting) into `first argument second argument`, or an argument list of `"*"` into a list of files in the current directory). – Charles Duffy Feb 22 '18 at 15:46
  • Likewise, this explanation ignores the bugs in `[ ! -e $1 ]`, which splits the first argument into a set of words, expands each such word as a glob, and passes each result of that glob as a separate argument to `[`. – Charles Duffy Feb 22 '18 at 15:47
  • I guess so ...... – Stephen C Feb 22 '18 at 15:53
  • thanks for your help! – Markos446 Feb 22 '18 at 16:01