ls with numeric range doesn't work inside bash script

后端 未结 4 550
星月不相逢
星月不相逢 2020-12-21 07:03

I have a folder with files named as file_1.ext...file_90.ext. I can list a range of them with the following command:

$ ls /home/rasoul/myfolder/         


        
4条回答
  •  醉酒成梦
    2020-12-21 07:31

    BASH always does brace expansion before variable expansion which is why ls is looking for a file /home/rasoul/myfolder/file_{6..19}.ext.

    I personally use seq when I need to expand a number range that has variables in it. You could also use eval with echo to accomplish the same thing:

    eval echo {$st..$ed}
    

    But even if you used seq in your script, ls would not iterate over your range without a loop. If you want to check if files in the range exist, I would also avoid using ls here as you will get errors for every file in the range that doesn't exist. BASH can check if a file exists using -e.

    Here is a loop that would check if a file exists within the range between variables $st and $ed and print it if it does:

    for n in $(seq $st $ed); do 
        f="${DIR}/file_$n.ext"
        if [ -e $f ]; then
            echo $f
        fi
    done
    

提交回复
热议问题