There are some fancy spinners and I bet every answer is spot on, especially @Jeff Schaller's, but personally as a developer I like being able to read the code and know exactly what's going on. I wanted a bash script to copy all my git repos into a temp zip when I start up my terminal and I also wanted a cool spinner to go with it and I'm not sure if my code is the most compact, but it definitely works well and is simple enough to read.
I'm not the most knowledgeable in bash, but I think the biggest problems are
- running while loop in the background (could be costly to CPU, but who knows?)
- I can still move my cursor around and that is annoying
- and if I wanted more than one process to happen I'm not exactly sure how to go about that
function runCommand() {
load & # calls the loading function
local whilePID=$! # gets the pid for the loop
tar -czf ${zipFileToUpdate} ${directoryToBackUp} & # backs up files
local backupPID=$! # get's back up pid
wait $backupPID # waits for backup id
kill $whilePID # kills the while loop
echo -ne "done" # echos done and removes the spinner
}
function load() { # just a function to hold the spinner loop, here you can put whatever
while true; do
echo -ne "/\r"
sleep .1
echo -ne "-\r"
sleep .1
echo -ne "\ \r"
sleep .1
echo -ne "|\r"
sleep .1
done
}
runCommand
^ To touch on the last issue I mentioned about multiple commands, I think I would personally put all my commands in a function and then run the function in the background, but they may have a bunch of different PID's
EXP:
function allCommands() {
command1;
command2;
command3;
...;
}
Then in the runCommands()
function
function runCommand() {
load & # calls the loading function
local whilePID=$! # gets the pid for the loop
allCommands & # run function w/ all cmds
local allCmdPID=$!
...
}
The variable allCmdPID
probably won't be the same as the commands switch and you'll likely wait for the first command and then terminate the loading loop, all while the other commands are still running. Possible work around is:
- getting an array of commands in for loop
- get pid of the command
- wait for it
- then move on to next command
But that all seems very tedious.