Search code examples
bashargumentsexit

how to exit if there is no argument in bash shell script?


i have written code to count the number of files and directories, but im struggling to make it exit if no argument is given. here is what i have right now, with the first is statement being the problem. how can i change this if statement to make it exit if no argument is given?

#!/bin/bash
if [$# -eq 0];
 echo "no arguments"
 exit 1
fi
cd "$1" || exit
n=0
m=0
for d in *;
do
    if [ -d "$d" ]; then
        n=$((n+1))
    else
        m=$((m+1))
    fi
done
echo "Files $m"
echo "Directories $n"

Solution

  • The syntax is: if [ $# -eq 0 ]; then.

    The spaces are not optional and nor is the then. So the beginning of your script should be:

    #!/bin/bash
    if [ $# -eq 0 ]; then
     echo "no arguments"
     exit 1
    fi