Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way for verbose mode in scripts?

When I write bash scripts I usually get the verbose mode this way (simplified):

_V=0  while getopts "v" OPTION do   case $OPTION in     v) _V=1        ;;   esac done 

and then every time I want a "verbose output" I type this:

[ $_V -eq 1 ] && echo "verbose mode on" || echo "verbose mode off" 

or for example this:

[ $_V -eq 1 ] && command -v || command 

Is there a way to do it more elegant? I was thinking about defining a function named "verbose" and type it instead of [ $_V -eq 1 ], but this would only be a tiny improvement.

I'm sure, there is more common way to do it…

like image 922
tamasgal Avatar asked Dec 10 '11 10:12

tamasgal


People also ask

How do you run a script verbose?

The -v option tells the shell to run in verbose mode. In practice , this means that shell will echo each command prior to execute the command. This is very useful in that it can often help to find the errors.

What is the meaning of verbose mode?

In computing, Verbose mode is an option available in many computer operating systems and programming languages that provides additional details as to what the computer is doing and what drivers and software it is loading during startup or in programming it would produce detailed output for diagnostic purposes thus ...

How do I write a verbose in Bash?

Enabling verbose Mode. We can enable the verbose mode using the -v switch, which allows us to view each command before it's executed. This script checks whether or not the number entered as input is positive.

How do I set verbose mode?

Enable verbose status messages by using Registry EditorClick Start > Run. In the Open box, type regedit, and then click OK. On the Edit menu, point to New, and then click DWORD Value. Type verbosestatus, and then press ENTER.


1 Answers

As you noticed, you can define some log functions like log, log_debug, log_error, etc.

function log () {     if [[ $_V -eq 1 ]]; then         echo "$@"     fi } 

It can help increasing your main code readability and hide show\nonshow logic into logging function.

log "some text"

If _V(global variable) is equal 1 "some text" will be printed, in other case it will not.

like image 143
ДМИТРИЙ МАЛИКОВ Avatar answered Oct 26 '22 00:10

ДМИТРИЙ МАЛИКОВ