gitee.com/mirrors_u-root/u-root@v7.0.0+incompatible/cmds/core/sleep/sleep.go (about)

     1  // Copyright 2017 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Delay for the specified amount of time.
     6  //
     7  // Synopsis:
     8  //     sleep DURATION
     9  //
    10  // Description:
    11  //     If no units are given, the duration is assumed to be measured in
    12  //     seconds, otherwise any format parsed by Go's `time.ParseDuration` is
    13  //     accepted.
    14  //
    15  // Examples:
    16  //     sleep 2.5
    17  //     sleep 300ms
    18  //     sleep 2h45m
    19  //
    20  // Bugs:
    21  //     When sleep is first run, it must be compiled from source which creates a
    22  //     delay significantly longer than anticipated.
    23  package main
    24  
    25  import (
    26  	"errors"
    27  	"flag"
    28  	"log"
    29  	"time"
    30  )
    31  
    32  var errDuration = errors.New("invalid duration")
    33  
    34  func parseDuration(s string) (time.Duration, error) {
    35  	d, err := time.ParseDuration(s)
    36  	if err != nil {
    37  		d, err = time.ParseDuration(s + "s")
    38  	}
    39  	if err != nil || d < 0 {
    40  		return time.Duration(0), errDuration
    41  	}
    42  	return d, nil
    43  }
    44  
    45  func main() {
    46  	flag.Parse()
    47  
    48  	if flag.NArg() != 1 {
    49  		log.Fatal("Incorrect number of arguments")
    50  	}
    51  
    52  	d, err := parseDuration(flag.Arg(0))
    53  	if err != nil {
    54  		log.Fatal(err)
    55  	}
    56  
    57  	time.Sleep(d)
    58  }