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
3
  • 1
    Try to change it: if [ "$DIR" = $1 ] eq, actually -eq is for numbers Commented May 5, 2015 at 10:12
  • See unix.stackexchange.com/a/200295/100397 for the (working) code on which this broken sample is based Commented May 5, 2015 at 10:38
  • quote all your variable uses in all you bash scripts Commented May 5, 2015 at 10:47

1 Answer 1

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
1
  • It's always a good practice to check the numbers of parameters (if your script needs one) Commented May 6, 2015 at 7:12

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.