Why does this while loop not execute after the first loop?

Viewed 44

I need a script to make a screenshot every x seconds. In the code I'm using touch for simplicity.

When I run the code the first touch(screenshot 1) is run and a file is created. But after waiting 5 seconds it echo for screenshot 2 but touch isn't run. Because no file is created. I have no idea why this would be te case.

#!/usr/bin/env bash
file=$(date +%Y-%m-%d.%H:%M:%S)    
x=1    
while true
do    
  echo "screenshot $x"    
  touch $file.jpg    
  sleep 1      
  x=$[$x+1]    
done
1 Answers

You should re-assign ${file} every time the loop runs! You're assigning it outside the loop, so you're touching the same filename every time!

x=1

while true; do
  # Assign a new name (with a new timestamp) to $file, and a file
  # with a new name will be created!
  file=$(date +%Y-%m-%d.%H:%M:%S)

  echo "screenshot $x"

  touch $file.jpg

  sleep 1

  x=$(( x + 1 ))

done

Note: Your touch command WAS working, it was just applying the same filename. Hope this helps!

Related