Created
May 9, 2020 09:13
-
-
Save ceceppa/0a6ea6c36a2f477e1928462bb3af1315 to your computer and use it in GitHub Desktop.
Execute a bash command with a nice spinner util it's completed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # Shell colours | |
| RED='\033[1;31m' | |
| NC='\033[0m' | |
| GREEN='\033[0;32m' | |
| BLUE='\033[1;36m' | |
| MAGENTA='\e[35m' | |
| YELLOW='\e[93m' | |
| CYAN='\e[96m' | |
| # Symbols | |
| X_SYMBOL='\u2A2F' | |
| CHECK_SYMBOL='\u2713' | |
| # | |
| # Output the error using nice colours | |
| # | |
| function log_error() { | |
| if [ ! -z "$2" ]; then | |
| printf "\n\n${YELLOW}Command: ${NC} ${2}\n" | |
| cat /tmp/duca.log | |
| printf "\n\n${RED}${X_SYMBOL} $1${NC}\n\n" | |
| else | |
| printf "\n${RED}${X_SYMBOL} $1${NC}\n" | |
| printf "\n" | |
| fi | |
| # Restore the cursor | |
| tput cnorm | |
| exit 1 | |
| } | |
| # | |
| # Run the command passed as 1st argument and shows the spinner until this is done | |
| # | |
| # @param String $1 the command to run | |
| # @param String $2 the title to show next the spinner | |
| # @param String $3 if set to 1 it will not perform the check on the exit status of the function | |
| # | |
| function execute_and_wait() { | |
| # allowd you to be able to control the output the log | |
| eval $1 >>/tmp/running.log 2>>/tmp/running.log.error & | |
| pid=$! | |
| delay=0.05 | |
| frames=('\u280B' '\u2819' '\u2839' '\u2838' '\u283C' '\u2834' '\u2826' '\u2827' '\u2807' '\u280F') | |
| echo "$pid" >"/tmp/.spinner.pid" | |
| # Hide the cursor, it looks ugly :D | |
| tput civis | |
| index=0 | |
| framesCount=${#frames[@]} | |
| while [ "$(ps a | awk '{print $1}' | grep $pid)" ]; do | |
| printf "${YELLOW}${frames[$index]}${NC} ${GREEN}$2${NC}" | |
| let index=index+1 | |
| if [ "$index" -ge "$framesCount" ]; then | |
| index=0 | |
| fi | |
| printf "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b" | |
| sleep $delay | |
| done | |
| # Remove the spinner | |
| # printf " \b\n" | |
| # | |
| # Wait the command to be finished, this is needed to capture its exit status | |
| # | |
| wait $! | |
| # Do I have to check the exit status? | |
| exitCode=$? | |
| if [ -z "$3" ]; then | |
| if [ "$exitCode" -ne "0" ]; then | |
| msg=${3:-"$2 failed"} | |
| log_error "$msg" "$1" | |
| else | |
| # Print the "Waiting message" prefixed with the success symbol | |
| log_done "$2" | |
| fi | |
| else | |
| log_done "$2" | |
| fi | |
| # Restore the cursor | |
| tput cnorm | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment