3

how to deal with arguments when executing a script

my code is:

#!/bin/bash

DIR="$1"

if [ DIR eq $1 ]
then
    echo -n "total directories:" ; find $DIR -type d | wc -l
    echo -n "total files:" ; find $DIR -type f | wc -l
else
    echo " pass parameters"
fi

when I executed with the script name (./countfiledirs) it's showing as:

./countfiledirs: line 4: [: DIR: unary operator expected
 pass parameters

If I execute ./countfiledirs without passing arguments it should have to show like:

pls pass arguments.

If I execute ./countfiledirs with passing arguments as ./countfiledirs /usr/share it should have to show output like:

total directories:145
total files:254
terdon
  • 242,166

1 Answers1

4

Your error is here:

if [ DIR eq $1 ]

You are not using the variable, that's the simple string DIR. What you want is:

if [ "$DIR" = "$1" ]

However, since you are setting DIR="$1", that test will always be true by definition. Also, when $1 is empty, so will $DIR and the find command will be run on the current directory. For many versions of find, these commands are equivalent:

find . -name foo
find -name foo

In the absence of a target directory, find will search through ., the current directory. So, a working version of your script would be:

#!/bin/bash

## Avoid using UPPER CASE variable names in bash.
dir="$1"

## Check if $dir exists
if [ -e "$dir" ]
then
    printf "total directories: %s\n" $(find "$dir" -type d | wc -l)
    printf "total files: %s\n" $(find "$dir" -type f | wc -l)
else
    echo " pass parameters"
fi

The number of arguments passed to a bash script is saved as $#, so you could also do

if [ $# -lt 1 ]
then
    echo "pass parameters"
    exit
fi
terdon
  • 242,166