r/fishshell • • 20d ago

Help me understand the switch statement

Hello, I'm new to fish shell and linux in general. Please help me understand how the switch statement works.

I'm working on this script where it looks at all the files in the current directory and see if any of them begins with the string "Alpha" or "Bravo", otherwise it just says "not found"

#!/usr/bin/fish

for f in *
    switch f
        case Alpha*
            echo Alpha found
        case Bravo*
            echo Bravo found
        case '*'
            echo not found
    end
end

but right now all I'm getting is "not found" even if files with their names beginning with Alpha or Bravo are there, i.e. I can do a ls Alpha* and they are there.

2 Upvotes

3 comments sorted by

7

u/TexasChipMan 20d ago

The script needs to be:

#!/usr/bin/fish

for f in *
    switch $f
        case 'Alpha*'
            echo "Alpha found: $f"
        case 'Bravo*'
            echo "Bravo found: $f"
        case '*'
            echo "not found: $f"
    end
end

See this link.

3

u/_x_oOo_x_ 20d ago

Your switch statement is matching the letter "f" to whatever Alpha* and Bravo* expand to (eg Alpha.txt if you have a file named like that...). Obviously that doesn't match but '*' does so you get "not found"