1

I have a script when you select a desktop file, but when I run this case function:

File=$(yad --file);

if [[ "$File" =~ *".desktop" ]]; then
 echo "yes" 
else
 echo "no" 
if

and i try this :

File=$(yad --file);
case $File in 
   *.desktop )
   echo "yes"
    ;;
   * )
    echo "no"
   ;;
esac

it's always telling me that I have to try again I don't know what's the problem, can anyone help me?

3
  • 2
    Start by pasting this into shellcheck.net and fix all errors it shows you. I can see at least three syntax errors. Commented Feb 3, 2017 at 0:16
  • if/then is not a case statment. But you could use a case statement: case $File in *.desktop) echo yes;; *) echo no;; esac; Commented Feb 3, 2017 at 14:27
  • i already try it but the same problem is tell me to try again Commented Feb 3, 2017 at 15:24

1 Answer 1

2

I am not exactly sure what this script is supposed to do, but try this:

File="$(Yad --file)"

if [[ "$File" =~ .*[.]desktop$ ]]; then
 echo "yes" 
else
 echo "no" 
fi

Bash regular expression matching (=~) uses extended regular expressions, not glob expressions. To designate any sequence of zero or more characters, you need to use .*. The . means "any character", and the * means zero or more times. [.] designates a literal period, avoiding the "any character" meaning of . used alone. I also added an end-of-line anchor ($). This forces the pattern to match from the end of the filename, as you probably would want when matching with the extension.

There also is an error in your first line. There has to be no space between the $ sign and parentheses. And to close an if block, you need to use fi.

You can use glob-style matching with bash conditionals, just use an equal sign :

if [[ "$File" = *.desktop ]]; then
Sign up to request clarification or add additional context in comments.

6 Comments

No need for double quotes around variables inside [[ ]].
@codeforester I know, but it does not hurt either (aside from regex patterns, at least), and I am so used to quoting by now... For many people, quoting everywhere is probably easier to remember and safer than trying to remember what needs to be quoted and what doesn't.
@codeforester Except on the right side of ==/!=, if you want to prevent globbing.
@zakariagatter The script is Bash-specific, make sure you run it with Bash (and add #!/bin/bash as the first line).
@Fred I second your opinion about quoting. Why should we think about whether something is safe or not if we could simply quote? Thinking can be considered unsafe. ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.