I am trying to have a bash script that has a sequence of files in a directory and chooses 1 of them and outputs it to the terminal. Then on the next run, it chooses the next file in the sequence and outputs that file's name. Is it possible to do that? How can I have the bash program "remember" what file it chose to then choose the next one on the next script call?

  • 2
    use a text file to remember things
    – jsotola
    Commented Apr 6 at 19:59
  • 1
    That was my first thought. However, is there a better way without needing an external file? I don't have an issue doing so but I wanted to make sure there is another way. Commented Apr 6 at 20:03
  • Environmental/etc variable? Or, more dangerously, have the script over-write itself? Commented Apr 6 at 20:37
  • What if the latest file is deleted, renamed or the directory contents change?
    – Kate
    Commented Apr 6 at 20:45
  • 1
    A simple way: at the end of the script add an mv command to move the file to another directory.
    – dhm
    Commented Apr 6 at 21:34

1 Answer 1


Use a moving softlink.


ln -s file001 .thisone

In your script:

infile="$(stat -c "%N" .thisone)"
sequence=$( basename "$infile"  | sed -e 's%file0*%%' )
next=$((sequence + 1))
printf -v nextfile "file%03d" $next
rm -f .thisone
if [[ -f "$nextfile" ]] ; then
    ln -s "$nextfile" .thisone
    ln -s "file001" .thisone
# process $infile, .thisone next

UNTESTED, but shellcheck.net likes it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .