0

I have a directory full of random files. Some of them are pictures and end with .png extension. I want to create a bash script that deletes a random .png image every time I run it. How do I do this? Please explain your answer (or put appropriate links) since I'm a complete beginner.

IgnisDa
  • 80
  • 1
  • 6

2 Answers2

2

use the shuf command to create a random shuffle and head -1 to pick the top one

ls -1 *.png |  shuf | head -1

or

ls -1 *.png | shuf -n 1
FangQ
  • 1,444
  • 10
  • 18
0

Using just bash builtins to pick the file:

#!/usr/bin/env bash

shopt -s nullglob
files=(*.png)
shopt -u nullglob
if [[ ${#files[@]} -eq 0 ]]; then
  echo "No matching files!"
  exit
fi
file=${files[$((RANDOM % ${#files[@]}))]}
echo "Deleting $file"
rm -f "$file"

Adds all the matching files to an array (See How do I assign ls to an array in linux bash), and then picks a random one from it using the $RANDOM variable (Which evaluates to a new random integer each time it appears) and some math.

Shawn
  • 47,241
  • 3
  • 26
  • 60