Home > Net >  How to compare file names in SHELL SCRIPT
How to compare file names in SHELL SCRIPT

Time:09-17

I have two file names as

file1 = "my_random_forest_2021-08-11-094538.csv.zip"
file2 = "my_random_forest_2021-08-11-094538.csv.zip"

if [$file1 == $file2]; then
    echo "matched"

On executing the script it says:

test.sh: line 5: [my_random_forest_2021-08-11-094538.csv.zip: command not found

How to compare file names that comes with the above mentioned formats?

CodePudding user response:

The right syntax would be like this

file1="my_random_forest_2021-08-11-094538.csv.zip"
file2="my_random_forest_2021-08-11-094538.csv.zip"
if [ $file1 = $file2 ] 
then
    echo "matched"
fi

There is no whitespace while declaring a variable.
There should be whilespace between variables and square brackets.
; is not neccesory after if. if you want to add if and then in one line you can add;
Matching will be done using = not ==.
if should be ended with fi to close the statement.

CodePudding user response:

if [ "$file1" = "$file2" ]; then
echo "matched";
fi

You're missing a space between the square bracket and the variable name. Without the space the shell is interpreting "[my_random_forest_2021-08-11-094538.csv.zip" as a command (which doesn't exist).

  • Related