Bash countdown » Historie » Version 1
Jeremias Keihsler, 13.01.2017 10:46
| 1 | 1 | Jeremias Keihsler | h1. Bash countdown |
|---|---|---|---|
| 2 | |||
| 3 | This uses a few tricks to do what you want: |
||
| 4 | |||
| 5 | * The printf command does NOT append a linefeed automatically unless you tell it to. |
||
| 6 | * Setting IFS to something else lets the shell split things apart into arrays on whatever delimiter you want, in this case , :. |
||
| 7 | * The date command can be used to produce time in seconds. |
||
| 8 | * Carriage returns return the cursor to the beginning of the line without moving to the next line. |
||
| 9 | |||
| 10 | <pre> |
||
| 11 | function countdown |
||
| 12 | { |
||
| 13 | local OLD_IFS="${IFS}" |
||
| 14 | IFS=":" |
||
| 15 | local ARR=( $1 ) |
||
| 16 | local SECONDS=$(( (ARR[0] * 60 * 60) + (ARR[1] * 60) + ARR[2] )) |
||
| 17 | local START=$(date +%s) |
||
| 18 | local END=$((START + SECONDS)) |
||
| 19 | local CUR=$START |
||
| 20 | |||
| 21 | while [[ $CUR -lt $END ]] |
||
| 22 | do |
||
| 23 | CUR=$(date +%s) |
||
| 24 | LEFT=$((END-CUR)) |
||
| 25 | |||
| 26 | printf "\r%02d:%02d:%02d" \ |
||
| 27 | $((LEFT/3600)) $(( (LEFT/60)%60)) $((LEFT%60)) |
||
| 28 | |||
| 29 | sleep 1 |
||
| 30 | done |
||
| 31 | IFS="${OLD_IFS}" |
||
| 32 | echo " " |
||
| 33 | } |
||
| 34 | |||
| 35 | countdown "00:07:55" |
||
| 36 | </pre> |