NewLands
NewLands

Reputation: 73

if file name(just name) comparision shell script

another newbie in Linux shell scripting.

Basically I've a folder with many files in it. But I need to get only the files that ends with ".log"

Below is my version which doesn't work

#!/bin/sh
for i in *;
do
        if [ "$i" == "$i".log ]; then
                echo $i;
        fi
done

Could someone please help me on this ? Thanks a lot !

Upvotes: 0

Views: 410

Answers (2)

glenn jackman
glenn jackman

Reputation: 247210

@John3136 has the simplest answer. With bash, you would use the fact that == inside [[ ... ]] is actually a pattern matching operator, not an equality operator:

#!/bin/bash
for f in *; do
    if [[ "$f" == *.log ]]; then
        echo "$f"
    fi
done

See http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs

Upvotes: 0

John3136
John3136

Reputation: 29266

Any reason you can't you can't just do it like this?

for fname in *.log
do
    echo $fname
done

Upvotes: 3

Related Questions