How can I test if a variable contains a string in a bash script without getting the "command not found" error? [closed]

StackOverflow https://stackoverflow.com/questions/22717169

  •  23-06-2023
  •  | 
  •  

Question

I keep getting a "command not found" error after checking a variable for the substring .txt.

Here's a simple version of my script.

myscript.sh

#!/bin/sh
if [["$1" == *.txt]]
    then
    echo $1
fi

Result:

> ./myscript.sh argument.txt
./myscript.sh: line 2: [[argument.txt: command not found]]
Was it helpful?

Solution

The error is because of a space needed around the brackets [[ and ]]:

#!/bin/sh
if [[ "$1" == *.txt ]]
    then
    echo $1
fi

That is, instead of:

if [["$1" == *.txt]]

use

if [[ "$1" == *.txt ]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top