I wanted to make a CLI tool that will display a random quote (from a list of .sh scripts which show ANSI art along with said quote) and also let you filter by author.
It works fine when I pick an author and it has only 1 option to choose from, but once I try to randomize from multiple outputs, it acts weird. Here's the code
#!/usr/bin/env bash
# Variables
author=$1
quoteFiles=()
numberFiles=""
# Functions
findQuotes() {
# Save all paths for available quotes to array & filter by name.
readarray -d '' quoteFiles < <(find ~/quotes -name "*.sh" | grep "$author")
# Grab number of quotes.
local foundNum=$(find ~/quotes -name "*.sh" | grep "$author" | wc -l)
numberFiles=$foundNum
}
main() {
# Run function to save file paths to array & assign number of file paths to variable for checking
findQuotes
# Make random number between 1 and the total number of files.
randomNum=$(shuf -i 1-"$numberFiles" -n 1)
# Check if random number == line number, if it is: print that quote
for line in $(seq 1 $numberFiles)
do
echo $randomNum # TESTING PURPOSES REMOVE AFTER
echo $line # same
echo $quoteFiles[$line] # same
# Check if this array element corresponds with random number
#if [[ $line -eq $randomNum ]]
#then
# Run the specific sh script it found with a quote
# bash $quoteFiles[$line]
# fi
done
}
main
The issue seems to be with the array I'm making, since the test echo I made (echo $quoteFiles[$line] # same) prints all the elements and not just the one at that specific index. Here's the full response:
$ ./quoter
3
1
/Users/petal/quotes/bourdieu/education.sh /Users/petal/quotes/marx/fish.sh /Users/petal/quotes/seeger/side.sh [1]
3
2
/Users/petal/quotes/bourdieu/education.sh /Users/petal/quotes/marx/fish.sh /Users/petal/quotes/seeger/side.sh [2]
3
3
/Users/petal/quotes/bourdieu/education.sh /Users/petal/quotes/marx/fish.sh /Users/petal/quotes/seeger/side.sh [3]
I don't know what I'm doing wrong in making the array.
$quoteFiles[$line]is not how you access arrays in Bash. The correct syntax would be${quoteFiles[$line]}. Also, consider using (double) quotes around your variables to avoid word splitting at whitespace characters.