ls with numeric range doesn't work inside bash script

后端 未结 4 541
星月不相逢
星月不相逢 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:04

    Numeric ranges have to be literal numbers, you can't put variables in there. To do it you need to use eval:

    FILES=`eval "ls ${DIR}/file_{$st..$ed}.ext"`
    

    Here's a transcript of my test (I tried it in bash 4.1.5 and 3.2.48).

    imac:testdir $ touch file_{1..30}.ext
    imac:testdir $ st=6
    imac:testdir $ ed=20
    imac:testdir $ DIR=.
    imac:testdir $ FILES=`eval "ls ${DIR}/file_{$st..$ed}.ext"`
    imac:testdir $ echo "$FILES"
    ./file_10.ext
    ./file_11.ext
    ./file_12.ext
    ./file_13.ext
    ./file_14.ext
    ./file_15.ext
    ./file_16.ext
    ./file_17.ext
    ./file_18.ext
    ./file_19.ext
    ./file_20.ext
    ./file_6.ext
    ./file_7.ext
    ./file_8.ext
    ./file_9.ext
    imac:testdir $ 
    

提交回复
热议问题