Search code examples
fish

In fish shell, how to iterate over files using wildcard and variable?


If I run:

for f in *1000.png
   echo $f
end

I get

1000.png
11000.png
21000.png

I would like to do something like:

for i in 1 2 3
    for f in *$i000.png
         echo $f
    end
end

To get

1000.png
11000.png
21000.png
2000.png
12000.png
22000.png
3000.png
13000.png
23000.png

Instead, it outputs nothing.

I also tried:

for i in 1 2
    set name "*"$i"000.png"
    for f in (ls $name)
        echo $f
    end
end

Outputting:

ls: *1000.png: No such file or directory
ls: *2000.png: No such file or directory

Solution

  • When you are attempting to referencing the i variable in *$i000.png, your shell thinks that $i000 means you are trying to reference the i000 variable, not i followed by three zeroes like you want.

    Use {$var_name} to access variables in fish, generally its a good idea to always reference shell variables this way.

    So your your case, in the second line use:

        for f in *{$i}000.png