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.
Asked
Active
Viewed 951 times
0

IgnisDa
- 80
- 1
- 6
-
What have you tried so far? – oguz ismail Apr 18 '20 at 13:56
-
I tried something using the shuf command but couldn't get it to work – IgnisDa Apr 18 '20 at 13:57
-
Something like `ls *.png | shuf -n 1 | xargs rm -v --`? Not really a good solution though – oguz ismail Apr 18 '20 at 14:00
-
I'll just have to type that out in a terminal because I have no idea what xargs or even the '|'s mean – IgnisDa Apr 18 '20 at 14:13
2 Answers
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
-
-
-
I tried the second one, and it gave me shuf: invalid line count: ‘-1’. I replaced the last - 1 with 1 and it worked. – IgnisDa Apr 18 '20 at 14:19
-
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