-1

So far I have the following code:

    #!/bin/bash
    echo "Adding new path...."
    if [[$# -eq1] || [$# -eq2]] 
    then
    if [$# -eq2] 
    then
    export PATH=$PATH:/$1:/$2
    fi
    if [$# -eq1] 
    then
    export PATH=$PATH:/$1
    fi
    else echo "Incorrect number of parameters. No more than two     directories can be added at once."
    fi
     echo $PATH
     exit 0

When I run this script passing it one parameter i get an error: "./addDir: line 3: [[1: command not found ./addDir: line 3: [1: command not found "

when I run it with 2 parameters instead of "1" it says "2"

What's going on?

C. Suarez
  • 11
  • 1
  • 5
  • You need way more spaces on those conditions. `if [[ $# -eq 1 || $# -eq 2 ]]` – Kevin Sep 21 '17 at 02:04
  • @Kevin (I think) that really should have been an answer – David Z Sep 21 '17 at 02:05
  • 1
    https://stackoverflow.com/questions/18568706/check-number-of-arguments-passed-to-a-bash-script/18568726 – xiaobing Sep 21 '17 at 02:08
  • @DavidZ eh, I don't really have the patience to explain it right now. – Kevin Sep 21 '17 at 02:08
  • @Kevin Sure, but I don't think that matters - the text you posted in the comment box could have been copied and pasted into the answer box and it would make a valid, albeit minimal, answer. – David Z Sep 21 '17 at 02:11

1 Answers1

2

You're missing some spaces. Basically, if you're trying to use the [...] construction, you need to have spaces before and after each bracket - think of [ as being the name of a command, in the same way as echo, and ] as being an argument to that command. (In fact, there might actually be a /bin/[ program on your system.) Just as you can't type echofoo and expect it to run the echo program, similarly you can't type [[$# if you expect it to run [.

In your case, you'd need to do things like

if [ $# -eq 2 ]; ...

And for the compound test you're doing in line 3, I don't think you can use [ and ] within the test. In other words, don't use those brackets for grouping; it has to be [ something ] where the something doesn't contain any brackets. Read the relevant section of the bash man page for the full details of what you can put there.

There is also a shell construct [[ ... ]] which does basically the same thing but has different syntax. You could use that instead, but be aware that it's very different from [ ... ].

David Z
  • 128,184
  • 27
  • 255
  • 279