Dark Matter
Dark Matter

Reputation: 2311

Counting the number of files in a directory in bash

I have a bash script where I'm trying to find out the number of files in a directory and perform an addition operation on it as well.

But while doing the same I'm getting the error as follows:

admin> ./fileCount.sh
       1
./fileCount.sh: line 6: 22 + : syntax error: operand expected (error token is " ")

My script is as shown:

#!/usr/bin/bash

Var1=22
Var2= ls /stud_data/Input_Data/test3 | grep ".txt" | wc -l 

Var3= $(($Var1 + $Var2))
echo $Var3

Can anyone point out where is the error.

Upvotes: 0

Views: 194

Answers (2)

F. Hauri  - Give Up GitHub
F. Hauri - Give Up GitHub

Reputation: 71007

A little away

As @devnull already answered to the question point out where is the error,

Just some more ideas:

General

To make this kind of browsing, there is a very powerfull command find that let you find recursively, exactly what you're serching for:

Var2=`find /stud_data/Input_Data/test3 -name '*.txt' | wc -l`

If you won't this to be recursive:

Var2=`find /stud_data/Input_Data/test3 -maxdepth 1 -name '*.txt' | wc -l`

If you want files only (meaning no symlink, nor directories)

Var2=`find /stud_data/Input_Data/test3 -maxdepth 1 -type f -name '*.txt' | wc -l`

And so on... Please read the man page: man find.

Particular solutions

As your question stand for , there is some bashism you could use to make this a lot quicker:

#!/bin/bash

Var1=22

VarLs=(/stud_data/Input_Data/test3/*.txt)

[ -e $VarLs ] && Var2=${#VarLs[@]} || Var2=0

Var3=$(( Var1 + Var2 ))

echo $Var3

# Uncomment next line to see more about current environment
# set | grep ^Var

Where bash expansion will translate /path/*.txt in an array containing all filenames matching the jocker form.

If there is no file matching the form, VarLs will only contain the jocker form himself.

So the test -e will correct this: If the first file of the returned list exist, then assing the number of elements in the list (${#VarLs[@]}) to Var2 else, assign 0 to Var2.

Upvotes: 3

devnull
devnull

Reputation: 123628

Can anyone point out where is the error.

  • You shouldn't have spaces around =.
  • You probably wanted to use command substitution to capture the result in Var2.

Try:

Var1=22
Var2=$(ls /stud_data/Input_Data/test3 | grep ".txt" | wc -l)

Var3=$(($Var1 + $Var2))
echo $Var3

Moreover, you could also say

Var3=$((Var1 + Var2))

Upvotes: 2

Related Questions