Touch files reverse

Discussion in 'Programming & Software Development' started by spotted, Jan 1, 2021.

  1. spotted

    spotted Member

    Joined:
    Nov 10, 2010
    Messages:
    414
    Location:
    Sydney
    I'm trying to do a very simple thing. Touch files starting from the last.

    The basic script is
    `
    for i in *
    do
    touch "$i"
    sleep 0.1
    done;
    `

    But I want it reversed, so that if listing files in time order they are also in alpha order.
    I found I could use ls -1r

    So I got
    `
    for i in "$(ls -1r)"
    do
    touch "$i"
    #echo $i
    sleep 0.1
    done;
    `

    If I run this with echo it's perfect.
    When I run with touch, it does the files, then creates 1 new file which is all the filenames concat.

    I'm using cygwin.
    No idea why this extra listing comes?
     
  2. elvis

    elvis Old school old fool

    Joined:
    Jun 27, 2001
    Messages:
    43,807
    Location:
    Brisbane
    In BASH, "for" expects a space delimited list without quotes. Your expanded shell here - everything inside $() - is quoted, thus becoming a single concatenated list that will be touched as one long filename.

    Remove the quotation marks around it, and the items will be touched individually. Note however that if there are spaces in any of the file names, it'll break.

    In that case, try instead:

    Code:
    ls -1r | while read FILENAME
    do
      touch "${FILENAME}"
      sleep 0.1
    done
    
     
    Last edited: Jan 1, 2021
    grs1961 likes this.
  3. OP
    OP
    spotted

    spotted Member

    Joined:
    Nov 10, 2010
    Messages:
    414
    Location:
    Sydney
    Thanks that one works great!
     

Share This Page

Advertisement: