Bash Scripting Bits Part 1

A script that renames files to a random number. Then renames files sequentially. A special (sponsored) file is inserted at intervals in the directory

Declare variables as integers

How to declare variables and initialize some to zero.

declare -i filenumber=0
declare -i sponsornumber=0
declare -i counter=0
declare -i directory_size

Assign a string to a variable


Calculate the directory size where the files are stored

directory_size="$(ls -l ./ | grep 'jpg' | wc -l)"

Rename files in the directory to a random number

for file in *.jpg; do
  mv "$file" "$number$filetype"

Use a random number within a range

Random number from 1 to 10:

number="$(((RANDOM % 10) + 1))"

Random number from 1 to 100:

number="$(((RANDOM % 100) + 1))"

Rename files into a sequential number 1, 2, 3…etc

for file in *.jpg; do
  filenumber="$(($filenumber + 1))"
  mv "$file" "$filenumber$filetype"

Insert files at intervals in current directory

Copy “sponsored” files in this sequence: 2, 8, 14…etc.

The sequence requires the algorithm: 2 + (6 * n)

The files are copied like this: 2a, 8a, 14a.

while [ $counter -lt $directory_size ]; do
  sponsornumber="$(((6 * $counter) + 2))"
  cp sponsor_directory/sponsor_file.jpg "$sponsornumber"a"$filetype"
  counter="$(($counter + 1))"

Leave a Reply