Tell me more ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I need to write a simple homework script for my Unix 101 course. I need to take a directory name from the user, and list how many things are in it. For some reason it doesn't work and gets the next error message:

line 3: [: missing `]'
line 9: [: missing `]'

I tried a lot of things around the brackets. By the examples I found on the net, this should work though.

#!bin/bash

if [ $# -ne 1 ]
then
echo "Usage: $0 {dirname}"
exit 1
fi

if [ -d "$1" ]
then
echo `ls -l $1 | wc -l`
else
echo "$1 directory not found!"
fi
share|improve this question
2  
What is the question or the error ? Indenting code is not just an option, please help you & us by indenting it. – sputnick Oct 19 '12 at 0:09
How do you run your script ? – sputnick Oct 19 '12 at 0:11
i did chmod +x filename on it, then I run it by ./filename – vernon Oct 19 '12 at 0:13
2  
@Sigur : it's the number of arguments. – sputnick Oct 19 '12 at 0:13
1  
change the shebang to #!/bin/bash -x to debug it. – sputnick Oct 19 '12 at 0:24
show 8 more comments

closed as not constructive by bahamat, jasonwryan, Renan, Gilles, warl0ck Oct 19 '12 at 1:17

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or specific expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, see the FAQ for guidance.

2 Answers

Below is the right script and it's correction inline:

#!/bin/bash    
# A slash is missing before "bin"

if [[ $# -ne 1 ]] # In bash use [[ and ]] instead
then
  echo "Usage: $0 {dirname}"
  exit 1
fi

if [[ -d "$1" ]]
then
    ls -l "$1" | wc -l  # a command output don't need echo again
else
    echo $1 directory not found  # !" would fail as ! indicate an event
fi

P.S For listing total files count in a directory, use something like this:

FILES=($1/*); echo $#{FILES[@]}, it's much faster

share|improve this answer

My conclusion after reading your question is that you did one of two things wrong:

share|improve this answer

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