title | author | date |
---|---|---|
BASH-BOOST(1) |
github.com/tomocafe |
September 9, 2024 |
Routines for parsing command line arguments
Example:
bb_setprog "myprogram"
bb_addopt f:foo "Number of foos (default: 2)" 2
bb_addflag b:bar "Bar flag"
bb_setpositional "THINGS" "Things to process"
bb_parseargs "$@"
set -- "${BB_POSARGS[@]}" # $@ now only contains the positional arguments
bb_checkopt bar && echo "You gave the bar flag!"
bb_getopt -v fooval foo
[[ $fooval -gt 0 ]] || bb_errusage "foo val must be greater than 0"
echo "You set foo to $fooval"
for arg in "$@"; do
echo "You have item $arg"
done
Example:
bb_setprog "copy"
bb_addflag "f:force" "force overwrite destination"
bb_addarg "src" "source file/directory"
bb_addarg "dst" "destination path"
bb_parseargs "$@"
bb_getopt -v src src || bb_errusage "missing required src argument"
bb_getopt -v dst fst || bb_errusage "missing required dst argument"
[[ -e "$dst" && ! bb_checkopt force ]] && bb_fatal "$dst exists"
cp "$src" "$dst"
Adds a command line option to be parsed
Arguments:
SHORTNAME
: optional single character, e.g. "f" for an -f FOO optionLONGNAME
: required long name, e.g. "foo" for a --foo FOO optionDESCRIPTION
: description of the option used in helpDEFAULT
: the default value of the option if not given in the command line
Notes:
-h and --help are reserved for automatically-generated command usage and help
Adds a named argument
Arguments:
NAME
: unique, one-word name of the argumentDESCRIPTION
: description of the argument used in helpDEFAULT
: default value if not given in the command line
Adds a command line flag to be parsed
Arguments:
SHORTNAME
: optional single character, e.g. "f" for an -f flagLONGNAME
: required long name, e.g. "foo" for a --foo flagDESCRIPTION
: description of the option used in help
Notes:
-h and --help are reserved for automatically-generated command usage and help
Print the command line usage string
Print the command line help
Notes:
Includes the usage string and a list of flags and options with their descriptions.
Issues an error message, prints the command usage, and exits the shell
Arguments:
MESSAGE
: error message to be printedRETURNVAL
: return code to exit with (defaults to 1)
Check if LONGNAME is a registered flag (not an option)
Returns: 0 if LONGNAME is a flag, 1 otherwise (i.e. it is an option)
Sets the name of the program for printing usage and help
Arguments:
PROGNAME
: name of the program (defaults to current script name)
Sets the name and description of the positional arguments
Arguments:
NAME
: one-word name of the positional arguments (auto-capitalized)DESCRIPTION
: description of the positionals used in help
Parses command line arguments after registering valid flags and options
Arguments:
ARGS
: the list of command line arguments, usually "$@"
Notes:
- Check flags with
bb_checkopt LONGNAME
- Get option setting values or named arguments with
bb_getopt LONGNAME
- Get positional arguments with
${BB_POSARGS[@]}
array - If the last argument is a single dash (-), read remaining arguments from stdin
Parses arguments in $@ and modifies it in-place to only hold positional arguments
Notes:
To use this in a script, you must do shopt -s expand_aliases
Gets the value of option or argument by name
Arguments:
VAR
: variable to store result (if not given, prints to stdout)LONGNAME
: long name of the option (or named argument)
Returns: true if the result is nonempty
Returns the value of flag named LONGNAME
Arguments:
LONGNAME
: long name of the flag
Returns: the flag value, either true or false
Notes:
Undefined if used on an opt instead of a flag
Clears all registered argument parsing settings
Notes:
Only one "command" can be registered for parsing at once so this can be used to clear the state of a previous command and start a new one
Routines for printing text in color using ANSI escape codes
Prints the given text in color if outputting to a terminal
Arguments:
COLORSTR
: FGCOLOR[on[BGCOLOR]] (e.g. red, bright_red, white_on_blue)TEXT
: text to be printed in color
Returns: 0 if text was printed in color, 1 otherwise
Notes:
Supported colors:
- black
- red
- green
- yellow
- blue
- magenta
- cyan
- bright_gray (dark_white)
- gray (bright_black)
- bright_red
- bright_green
- bright_yellow
- bright_blue
- bright_magenta
- bright_cyan
- white (bright_white)
This does not print a new line at the end of TEXT
Like colorize but always uses prints in color
Arguments:
COLORSTR
: FGCOLOR[on[BGCOLOR]] (e.g. red, bright_red, white_on_blue)TEXT
: text to be printed in color
Notes:
Use this instead of colorize if you need to still print in color even if not connected to a terminal, e.g. when saving the output to a variable. See colorize for supported colors
Strips ANSI color codes from text colorized by colorize (or rawcolor)
Arguments:
TEXT
: text possibly with color escape codes to be removed
Notes:
This is only guaranteed to work on text generated by colorize and variants, not for any generic string with ANSI escape codes.
Routines for handling user input
Prompts for input and saves the response to VAR
Arguments:
VAR
: variable to store response into (do not include $)PROMPT
: text displayed to the user
Prompts user to confirm an action by pressing Y
Arguments:
PROMPT
: text displayed to the user
Returns: 0 if yes, 1 otherwise
Notes:
If you want the user to type "yes", use getinput and check their response
Prompts user to press a key to continue
Arguments:
PROMPT
: text displayed to the user Default: Press any key to continue
Messaging routines
Prints an informational message to stderr
Arguments:
MESSAGE
: message to be printed
Prints a warning message to stderr
Arguments:
MESSAGE
: message to be printed
Prints an error message to stderr
Arguments:
MESSAGE
: message to be printed
Prints an error message to stderr and then exits the shell
Arguments:
MESSAGE
: message to be printedRETURNCODE
: return code to exit with (defaults to 1)
Issues a fatal error if two given values are not equal
Arguments:
VAL1
: value to checkVAL2
: value to check against (golden answer)MESSAGE
: optional prefix to the error messageRETURNCODE
: return code to exit with (defaults to 1)
Issues a fatal error if a given substring is not found in some given text
Arguments:
TEXT
: text to checkPATTERN
: substring to be foundMESSAGE
: optional prefix to the error messageRETURNCODE
: return code to exit with (defaults to 1)
Issues a fatal error if text does not match the given regular expression
Arguments:
TEXT
: text to checkPATTERN
: regular expressionMESSAGE
: optional prefix to the error messageRETURNCODE
: return code to exit with (defaults to 1)
Sets the current log level
Arguments:
LEVEL
: integer representing the current log verbosity level (default: 0)
Assigns a name to the given log level
Arguments:
LEVEL
: integer representing the current log verbosity levelNAME
: name to be assigned
Issues a message at a certain log level
Arguments:
LEVEL
: minimum logging level required to print the messageMESSAGE
: message to be printed
Notes:
Set BB_LOG_TIMEFMT to a valid time format string to override the default
Text-based progress bar and checkpoint pass/fail status line generator
Example:
ping -c 1 8.8.8.8 &>/dev/null; bb_checkpoint "Pinging DNS"
for pct in {0..100}; do sleep 0.1s; bb_progressbar $pct "Downloading"; done; echo
Prints/updates a progress bar
Arguments:
VALUE
: integer from 0 to 100; 100 meaning completeTEXT
: optional text to be displayed
Notes:
Customize the start, end, and fill characters by setting environment variables BB_PROGRESS_START, BB_PROGRESS_END, and BB_PROGRESS_FILL. By default these are set to [, ], and .
Prints a status line with pass/fail result based on RESULT
Arguments:
TEXT
: text to be displayedRESULT
: 0 for pass, nonzero for fail; if not given, infers from $?
Notes:
Customize the fill character and pass/fail text by setting environment variables BB_CHECKPOINT_FILL, BB_CHECKPOINT_PASS, and BB_CHECKPOINT_FAIL. By default these are set to space, OK, and FAIL.
Core routines
Loads a module or package
Arguments:
PKG
: either a package (e.g. cli/arg) or a whole module (e.g. cli)
Notes:
Each package only loads once; if you happen to load one twice, the second time has no effect
Checks if a package is loaded already
Arguments:
PKG
: package name in internal format, e.g. bb_cli_arg
Returns: 0 if loaded, 1 otherwise
Log text when debugging is enabled
Arguments:
TEXT
: message to be logged in debug mode
Notes:
Set environment variable BB_DEBUG to enable debug mode
Check if the script is being sourced
Returns: 0 if sourced, 1 otherwise
Print a stack trace to stderr
Clears all functions and variables defined by bash-boost
Directory bookmarking system
Adds a bookmark to the directory for quick recall
Arguments:
KEY
: single character to assign bookmark toDIR
: directory to bookmark; defaults to current directory
Notes:
If DIR is already bookmarked, this will clear the previously associated key If KEY is already used, this will overwrite the orevious assignment
Arguments:
KEY
: bookmark key to delete; prompts if unspecified
Notes:
Useful as a keyboard shortcut, e.g., Ctrl+X-B
Go to the directory bookmarked by KEY if it exists, otherwise create bookmark
Arguments:
KEY
: single character to assign bookmark to; prompts if unspecifiedDIR
: directory to bookmark; defaults to current directory
Notes:
If DIR is already bookmarked, this will clear the previously associated key. If KEY is already used but you wish to overwrite it, use bb_addbookmark or use bb_delbookmark KEY first Useful as a keyboard shortcut, e.g., Ctrl+B
Shows the current mapping of KEY, or all keys if KEY is unspecified
Arguments:
KEY
: bookmark key to show
Prints bookmark key assigned to the given DIR if such a bookmark exists
Arguments:
DIR
: directory to get assigned bookmark key of; defaults to current directory
Loads bookmark assignments from FILE
Arguments:
FILE
: a file containing bookmark assignments
Notes:
FILE should be formatted with an assignment on each line, with each assignment being a letter followed by a path, separated by space
Miscellaneous interactive commands
Make director(ies) and change directory to the last one
Arguments:
DIR
: usually a single directory to be made, but all arguments are passed to mkdir and the last argument is then passed to cd if mkdir is successful
Change directory up
Arguments:
DIR
: go to this directory, otherwise defaults to .. if no DIR specified
Notes:
Most useful with the associated command completion. After pressing TAB, the current working directory is populated, and with each further TAB, a directory is removed, moving you up the directory stack. Once you see the upward directory you want to go to, hit ENTER
Spawn a new terminal instance inheriting from this shell's environment
Arguments:
ARGS
: arguments to be appended to the terminal launch command
Notes:
- Uses the BB_TERMINAL or TERMINAL environment variable as the command to launch the new terminal instance.
- Sets the BB_FORKDIR variable for the spawned shell to read. In your shell init file, you can detect when this variable is set and change to this directory, if desired.
- BB_TERMINAL can be a list with arguments, or a string which will be tokenized by space. If your arguments contain spaces, you will need to declare the variable as a list.
Routines for managing a dynamic shell prompt
Activates the registered dynamic prompt
Deactivates the registered dynamic prompt
Notes:
This will restore the prompt to the state it was in when loadprompt was called
Sets the left prompt to the output of the list of given functions
Arguments:
FUNCTION
: a function whose stdout output will be added to the prompt
Notes:
The prompt areas are as follows:
+----------------------------------------+
| left prompt right prompt |
| nextline prompt |
+----------------------------------------+
Sets the right prompt to the output of the list of given functions
Arguments:
FUNCTION
: a function whose stdout output will be added to the prompt
Sets the next line prompt to the output of the list of given functions
Arguments:
FUNCTION
: a function whose stdout output will be added to the prompt
Sets the window title to the output of the list of given functions
Arguments:
FUNCTION
: a function whose stdout output will used as the window title
Sets the tab title to the output of the list of given functions
Arguments:
FUNCTION
: a function whose stdout output will used as the tab title
Notes:
Not all terminals support this
Prints text in color, for use specifically in prompts
Arguments:
COLORSTR
: valid color string, see bb_colorizeTEXT
: text to be printed in color
Notes:
This is like colorize but adds [ and ] around non-printing characters which are needed specifically in prompts
Routines for checking and setting environment variables
Check if an environment variable is set or empty
Arguments:
VAR
: name of the variable to check (don't include $)
Returns: 1 if unset, 2 if set but empty, 0 otherwise
Check if COMMAND is a valid command
Arguments:
COMMAND
: name of command to check (e.g., ls)
Notes:
This could be an executable in your PATH, or a function or bash builtin
Checks if items are in the colon-separated path variable VAR
Arguments:
VAR
: path variable, e.g. PATH (do not use $)ITEM
: items to find in the path variable
Returns: 0 if all items are in the path, 1 otherwise
Prepends items to the colon-separated path variable VAR
Arguments:
VAR
: path variable, e.g. PATH (do not use $)ITEM
: items to add to the path variable
Appends items to the colon-separated path variable VAR
Arguments:
VAR
: path variable, e.g. PATH (do not use $)ITEM
: items to add to the path variable
Prepends unique items to the colon-separated path variable VAR
Arguments:
VAR
: path variable, e.g. PATH (do not use $)ITEM
: items to add to the path variable
Notes:
If an item is already in the path, it is not added twice
Appends unique items to the colon-separated path variable VAR
Arguments:
VAR
: path variable, e.g. PATH (do not use $)ITEM
: items to add to the path variable
Notes:
If an item is already in the path, it is not added twice
Removes items from the colon-separated path variable VAR
Arguments:
VAR
: path variable, e.g. PATH (do not use $)ITEM
: items to remove from the path variable
Returns: 0 if any item was removed, 1 otherwise
Swaps two items in a colon-separated path variable VAR
Arguments:
VAR
: path variable, e.g. PATH (do not use $)ITEM1
: first item to swapITEM2
: second item to swap
Returns: 0 if swap is successful, 1 if either ITEM1 or ITEM2 was not in the path 2 if insufficient arguments were supplied (less than 3) 3 for internal error
Prints a path variable separated by SEP, one item per line
Arguments:
VAR
: path variable, e.g. PATH (do not use $)SEP
: separator character, defaults to :
Routines for common file operations
Resolves . and .. in a given absolute path
Arguments:
VAR
: variable to store result (if not given, prints to stdout)PATH
: an absolute path
Returns: 1 if PATH is invalid, 0 otherwise
Returns the absolute path from a relative one
Arguments:
VAR
: variable to store result (if not given, prints to stdout)TARGET
: target relative path (can be file or directory)FROM
: the absolute directory path from which the absolute path is formed (Defaults to $PWD)
Returns the relative path from a directory to the target
Arguments:
VAR
: variable to store result (if not given, prints to stdout)TARGET
: target absolute path (can be file or directory)FROM
: the absolute directory path from which the relative path is formed (Defaults to $PWD)
Returns: 1 if either TARGET or FROM is invalid, 0 otherwise
Prints a pretty version of the path
Arguments:
PATH
: a path
Notes:
Replaces home directory with ~
Counts the number of lines in a list of files
Arguments:
FILENAME
: a valid filename
Returns: 1 if any of the filenames are invalid, 0 otherwise
Counts the number of matching lines in a list of files
Arguments:
PATTERN
: a valid bash regular expressionFILENAME
: a valid filename
Returns: 1 if any of the filenames are invalid, 0 otherwise
Adds the file extension EXT to all given files
Arguments:
EXT
: the file extensionFILENAME
: a valid filename
Removes the last file extension from the given files
Arguments:
FILENAME
: a valid filename
Replaces symbolic links with deep copies
Arguments:
FILENAME
: a valid symbolic link
Returns the unresolved directory name of the current script
Arguments:
VAR
: variable to store result (if not given, prints to stdout)
Routines for parsing keyword arg strings
Example:
talk() {
bb_kwparse opts "$@"
set -- "${BB_OTHERARGS[@]}" # $@ now only contains non-kwargs
local verb="${opts[verb]:-have}"
local item
for item in "$@"; do
echo "You $verb $item"
done
}
talk eggs milk bread
talk verb=ate eggs milk bread
Parses a list of KEY=VAL pairs and stores them into a dictionary
Arguments:
MAP
: name of an associative array to be createdKEY=VAL
: a key-value pair separated by =ARGS
: other arguments not in KEY=VAL format are ignored
Notes:
Get non-keyword arguments with ${BB_OTHERARGS[@]}
Routines for common list operations
Joins the list of items into a string with the given separator
Arguments:
VAR
: variable to store result (if not given, prints to stdout)SEP
: separatorITEM
: a list item
Splits a string into a list based on a separator
Arguments:
LISTVAR
: list variable to store result (if not given, prints to stdout)SEP
: separatorSTR
: string to split
Checks if a target item exists in a given list
Arguments:
TARGET
: the search targetLIST
: a list item
Returns: 0 if found, 1 otherwise
Pushes an item to a list (stack)
Arguments:
LISTVAR
: name of the list variable (do not include $)ITEM
: item to push
Pops an item from a list (stack)
Arguments:
LISTVAR
: name of the list variable (do not include $)
Unshifts an item from a list (stack)
Arguments:
LISTVAR
: name of the list variable (do not include $)ITEM
: item to unshift
Shifts an item from a list (stack)
Arguments:
LISTVAR
: name of the list variable (do not include $)
Sorts the items of a list in lexicographic ascending order
Arguments:
LISTVAR
: list variable to store result (if not given, prints to stdout)ITEM
: a list item
Sorts the items of a list in lexicographic descending order
Arguments:
LISTVAR
: list variable to store result (if not given, prints to stdout)ITEM
: a list item
Sorts the items of a list in numerical ascending order
Arguments:
LISTVAR
: list variable to store result (if not given, prints to stdout)ITEM
: a list item
Sorts the items of a list in numerical descending order
Arguments:
LISTVAR
: list variable to store result (if not given, prints to stdout)ITEM
: a list item
Sorts the items of a list in human-readable ascending order
Arguments:
LISTVAR
: list variable to store result (if not given, prints to stdout)ITEM
: a list item
Notes:
Human readable, e.g., 1K, 2M, 3G
Sorts the items of a list in human-readable descending order
Arguments:
LISTVAR
: list variable to store result (if not given, prints to stdout)ITEM
: a list item
Notes:
Human readable, e.g., 1K, 2M, 3G
Filters an unsorted list to include only unique items
Arguments:
LISTVAR
: list variable to store result (if not given, prints to stdout)ITEM
: a list item
Filters an sorted list to include only unique items
Arguments:
LISTVAR
: list variable to store result (if not given, prints to stdout)ITEM
: a list item
Notes:
Faster than uniq, but requires the list to be pre-sorted
Checks if the variable with the given name is a list with >1 element
Arguments:
LISTVAR
: name of a variable
Notes:
This will return false if the variable is declared as a list but only has 1 element. In that case, you can treat the variable as a scalar anyway.
Assigns new variable names to items
Arguments:
ITEM
: a list itemNAME
: a variable name
Example:
func() {
bb_rename "$@" -- first second
echo "The first argument is $first"
echo "The second argument is $second"
}
Unpacks list items into named variables
Requires: bash 4.3 or later
Arguments:
LISTVAR
: name of the list variable (do not include $)NAME
: a variable name to hold a list element
Maps a function over a list, modifying it in place
Requires: bash 4.3 or later
Arguments:
LISTVAR
: name of the list variable (do not include $)FUNCTION
: a function or command to map a list element to a new value
Maps a function over a list of keys to generate an associative array
Requires: bash 4.3 or later
Arguments:
LISTVAR
: name of an associative array variable (do not include $)FUNCTION
: a function or command to map keys to valuesKEYS
: keys which will be added to the associative array with mapped values
Returns a reversed version of the given list
Arguments:
LISTVAR
: name of the returned reversed list variable (do not include $)ITEM
: list items to reverse
Routines for common math operations
Returns the sum of the given numbers
Arguments:
VAR
: variable to store result (if not given, prints to stdout)NUM
: a valid number
Returns the minimum of the given numbers
Arguments:
VAR
: variable to store result (if not given, prints to stdout)NUM
: a valid number
Returns the maximum of the given numbers
Arguments:
VAR
: variable to store result (if not given, prints to stdout)NUM
: a valid number
Returns the absolute value of a given number
Arguments:
VAR
: variable to store result (if not given, prints to stdout)NUM
: a valid number
Checks if all the given numbers are valid integers
Arguments:
NUM
: a number to check
Returns: 0 if all arguments are integers, 1 otherwise
Converts numbers from hexademical (base 16) to decimal (base 10)
Arguments:
LISTVAR
: list variable to store result (if not given, prints to stdout)NUM
: a number to convert
Returns: 1 if any number is invalid hexadecimal, 0 otherwise
Converts numbers from decimal (base 10) to hexademical (base 16)
Arguments:
LISTVAR
: list variable to store result (if not given, prints to stdout)NUM
: a number to convert
Returns: 1 if any number is invalid decimal, 0 otherwise
Converts numbers from octal (base 8) to decimal (base 10)
Arguments:
LISTVAR
: list variable to store result (if not given, prints to stdout)NUM
: a number to convert
Returns: 1 if any number is invalid octal, 0 otherwise
Converts numbers from decimal (base 10) to octal (base 8)
Arguments:
LISTVAR
: list variable to store result (if not given, prints to stdout)NUM
: a number to convert
Returns: 1 if any number is invalid decimal, 0 otherwise
Routines for runtime profiling of bash scripts
Starts runtime profiling
Arguments:
LOGFILE
: (optional) file use to log profiling data Default: TMPDIR/bbprof.PID.out
Notes:
Use the bbprof-read utility script to parse and analyze profile data
Stops runtime profiling
Routines for generating random sequences
Returns a random non-negative integer between MIN and MAX
Arguments:
VAR
: variable to store result (if not given, prints to stdout)MAX
: the largest possible returned valueMIN
: the smallest possible returned value (defaults to zero)
Returns a random string of the given length
Arguments:
VAR
: variable to store result (if not given, prints to stdout)LENGTH
: length of the returned stringCHARSET
: string with all possible characters to use (defaults to all alphanumeric characters)
Loads a dictionary of words
Arguments:
FILENAME
: file containing words, one per line
Notes:
The dictionary file should contain one word per line
Returns a string containing non-repeated random words from a loaded word dictionary
Arguments:
VAR
: variable to store result (if not given, prints to stdout)COUNT
: number of returned wordsSEP
: separator to use between words (default is space)
Notes:
You must load a word dictionary with bb_loadworddict before using this
Routines for common string operations
Strips leading (left) whitespace from text
Arguments:
VAR
: variable to store result (if not given, prints to stdout)TEXT
: text to strip whitespace from
Strips trailing (right) whitespace from text
Arguments:
VAR
: variable to store result (if not given, prints to stdout)TEXT
: text to strip whitespace from
Strips leading and trailing whitespace from text
Arguments:
VAR
: variable to store result (if not given, prints to stdout)TEXT
: text to strip whitespace from
Reverses a string
Arguments:
VAR
: variable to store result (if not given, prints to stdout)TEXT
: text to reverse
Converts character to its ASCII decimal code
Arguments:
VAR
: variable to store result (if not given, prints to stdout)CHAR
: a single character
Converts ASCII decimal code to character
Arguments:
VAR
: variable to store result (if not given, prints to stdout)CODE
: an integer ASCII character code
Converts text from snake to camel case
Arguments:
VAR
: variable to store result (if not given, prints to stdout)TEXT
: text in snake case
Notes:
Leading underscores are preserved
Converts text from camel to snake case
Arguments:
VAR
: variable to store result (if not given, prints to stdout)TEXT
: text in camel case
Converts text into title case (every word capitalized)
Arguments:
VAR
: variable to store result (if not given, prints to stdout)TEXT
: text to transform
Notes:
This does not check the content of the words itself and may not respect grammatical rules, e.g. "And" will be capitalized
Converts text into sentence case (every first word capitalized)
Arguments:
VAR
: variable to store result (if not given, prints to stdout)TEXT
: text to transform
Performs URL (percent) encoding on the given string
Arguments:
VAR
: variable to store result (if not given, prints to stdout)TEXT
: text to be encoded
Decodes URL-encoded text
Arguments:
VAR
: variable to store result (if not given, prints to stdout)TEXT
: text to be decoded
Returns: 1 if the input URL encoding is malformed, 0 otherwise
Repeat TEXT NUM times
Arguments:
VAR
: variable to store result (if not given, prints to stdout)NUM
: repeat this many times (integer)TEXT
: text to repeat
Pad and center TEXT with FILL character to have WIDTH width
Arguments:
VAR
: variable to store result (if not given, prints to stdout)WIDTH
: width of the padded string resultTEXT
: text to displayFILL
: character used for padding (if not given, uses space)
Notes:
If the text cannot be perfectly centered, it will be pushed closer to the left side. TEXT may contain color codes.
Checks if VER1 is greater than or equal to VER2
Arguments:
VER1
: a version string (containing only numerals and delimeters)VER2
: another version string, usually a reference pointDELIM
: character(s) to delimit fields in the version string (default: .-_)
Returns: 0 if VER1 greater or equal to VER2, 1 otherwise
Notes:
Numeric comparison is used, so alphabetical characters are not supported
Routines for common time and date operations
Example:
bb_timefmt "%F %T" # e.g., 2022-11-20 16:53:30
bb_timefmt "%F %T" $(bb_now +1h) # one hour from now
bb_timefmt "%F %T" $(bb_now ^h) # end of the hour
bb_timefmt "%F %T" $(bb_now +1d) # one day from now
bb_timefmt "%F %T" $(bb_now ^d) # end of the day
bb_timefmt "%F %T" $(bb_now +2w ^d) # after two weeks, at end of day
Returns a timestamp relative to the current time (in seconds after epoch)
Arguments:
VAR
: variable to store result (if not given, prints to stdout)OFFSET
: {+,-}N{s,m,h,d,w}[^] where N is an integer
Returns: 1 if any offset is invalid, 0 otherwise
Notes:
s: seconds m: minutes h: hours d: days w: weeks Optional: trailing ^ rounds up; ^d is short for +0d^
Formats a timestamp into a desired date format
Arguments:
VAR
: variable to store result (if not given, prints to stdout)FORMAT
: date format string, refer to man strftimeTIMESTAMP
: epoch time, defaults to current time (now)
Formats a time delta into a desired format
Arguments:
VAR
:FORMAT
:TIME1
: if TIME1 not specified, this is interpreted as a duration in secondsTIME2
: if specified, TIME1 is the end timestamp and TIME2 is the start timestamp
Notes:
Capital letters D, H, M, S represent the partial value Lowercase letters d, h, m, s represent the total value
Example:
bb_now -v start
sleep 120s
bb_now -v end
bb_timedeltafmt -v elapsed "%H:%M:%S" end start
bb_timedeltafmt -v total_seconds "%s" end start
echo "elapsed time $elapsed, $total_seconds total seconds"
# above should print "elapsed time 00:02:00, 120 total seconds"