Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indenting Bash Script Output

I am attempting to write a bash script and I am having difficulty making the output look neat and organized. I could fall back on just using newlines, but I would much rather have output that was easy to read. For instance, when I run git clone ..., I want to first echo "Cloning repository" and then have the output of git indented. Example output:

Cloning repository...
    Initialized empty Git repository in /root/client_scripts/jojo/.git/
    remote: Counting objects: 130, done.
    remote: Compressing objects: 100% (121/121), done.
    remote: Total 130 (delta 13), reused 113 (delta 6)
    Receiving objects: 100% (130/130), 176.07 KiB, done.
    Resolving deltas: 100% (13/13), done.

Currently, it's all compressed with no indentation. Does anyone know how to do this? I attempted with sed and awk but it didn't seem to show any more output than just Initialized empty Git repository in /root/client_scripts/jojo/.git/. I would greatly appreciate any comments.

like image 493
Topher Fangio Avatar asked Nov 03 '09 22:11

Topher Fangio


People also ask

How do I indent a bash script?

press Ctrl-space at the top of the file. move the cursor to the bottom of the file. press Alt-x and type untabify then return. press Alt-x and type indent-region then return.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What is $() in bash script?

$() Command Substitution According to the official GNU Bash Reference manual: “Command substitution allows the output of a command to replace the command itself.

What does #$ mean in bash?

#$ does "nothing", as # is starting comment and everything behind it on the same line is ignored (with the notable exception of the "shebang"). $# prints the number of arguments passed to a shell script (like $* prints all arguments). Follow this answer to receive notifications. edited Jul 9 at 13:55.


2 Answers

Pipe through

sed "s/^/    /g"

This will replace the (zero-width) anchor for line start by four spaces, effectively adding four spaces at the start of the line.

(The g does this globally; without it, it will only do it once, which would do the first line.)

like image 192
Joey Avatar answered Oct 07 '22 15:10

Joey


A different solution that doesn't require sed:

command | (while read; do echo "    $REPLY"; done)
like image 30
Juliano Avatar answered Oct 07 '22 17:10

Juliano