Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a prefix to bash verbose mode

Tags:

bash

shell

I'm writing a script using verbose mode but I'd like to set a prefix to the command outputs (mainly to make the output look nicer).

For example, the script:

#!/bin/bash -v

pwd
hostname

This will give the output:

pwd
/home/username
hostname
myawesomehost

But I'd like the output (specifically with the $ sign):

$ pwd
/home/username
$ hostname
myawesomehost

Is there a way to set a prefix for the verbose output like this?

like image 245
Ell Neal Avatar asked Aug 27 '16 12:08

Ell Neal


People also ask

How do I run a script in verbose mode?

The -v option tells the shell to run in verbose mode. In practice, this means that the shell will echo each command prior to executing the command. This will be useful in locating the line of script that has created an error.

What does ${ 1 mean in bash script?

- 1 means the first parameter passed to the function ( $1 or ${1} ) - # means the index of $1 , which, since $1 is an associative array, makes # the keys of $1.

What does $# mean in bash?

$# is a special variable in bash , that expands to the number of arguments (positional parameters) i.e. $1, $2 ... passed to the script in question or the shell in case of argument directly passed to the shell e.g. in bash -c '...' .... .

What is shell verbose?

The verbose option specifies that you want to display detailed processing information on your screen. This is the default. When you run the incremental, selective, or archive commands, information is displayed about each file that is backed up. Use the quiet option if you do not want to display this information.


1 Answers

You can use PS4 with set -x (enable trace):

#!/bin/bash

# prompt for trace commands
PS4='$ '

# enable trace
set -x

# remaining script
pwd
hostname

This will produce output as:

$ pwd
/home/username
$ hostname
myawesomehost
like image 123
anubhava Avatar answered Sep 16 '22 16:09

anubhava