3

I have a little bash script and have $file and $file2 variable. This is file and I want to get first 3 letters of this file name. And I want to compare them:

I tried:

curfile=$(basename $file)  
curfilefirst3=${curfile:0:3}
curfile2=$(basename $file2)
curfile2first3=${curfile2:0:3}

if ((curfilefirst3 == curfile2first3 )); then

....

But I think have problems, how can I fix?

Thank you.

onur
  • 5,647
  • 3
  • 23
  • 46

2 Answers2

3

You're missing $ for the strings in the comparison and you'll need to wrap each string with " and the entire expression with []:

file="this.txt"
file2="that.txt"

curfile=$(basename $file)
curfilefirst3=${curfile:0:3}

curfile2=$(basename $file2)
curfile2first3=${curfile2:0:3}

echo $curfile2first3
echo $curfilefirst3

if [ "$curfile2first3" == "$curfilefirst3" ]
then
   echo "same!"
else
   echo "different!"
fi

It might be a good idea to read up on bash conditionals

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
1

Substring Extraction

${string:position} Extracts substring from $string at $position. However, if should use [ and not ( as in:

if [ $curfilefirst3 == $curfile2first3 ]; then

The corrected version:

#!/bin/bash
file=abcdef
file2=abc123456
curfile=$(basename $file)
curfilefirst3=${curfile:0:3}
curfile2=$(basename $file2)
curfile2first3=${curfile2:0:3}
echo $curfilefirst3
echo $curfile2first3
if [ $curfilefirst3 = $curfile2first3 ]; then
echo same
else
echo different
fi

It prints same So, works

Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69