Skip to content
Advertisement

Linux shell script, differences between two directories

I made this code

if [ $# -ne 2 ]; then
echo "use $0 dir1 dir2"
exit 1
fi

if [ ! -d $1 ]; then
echo "$1 nu este un director"
exit 1
fi

if [ ! -d $2 ]; then
echo "$2 nu este un director "
exit 1
fi

a=0
k=1
for $1 in `ls`
do
if [ -f $1 ];  then
a=`exp $a + 1`
fi
done
echo "Ther are $a file "

I want to compare two folders and the folder are arguments to the command line.. it should be something like this : ./script.sh dir1 dir2

But i have this eror :

**./director.sh: line 29: `$1′: not a valid identifier **

I want to count the file from dir1 who is argument to the command line.

Can someone help me please ?

Advertisement

Answer

This is the main error:

for $1 in `ls`
  1. $1 is not a valid variable name
  2. don’t parse ls

Do this instead

for file in *

Also, quote your variables: you want to protect your script from any filenames containing whitespace.

if [ ! -d "$1" ]
if [ -f "$file" ]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement