Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indenting multi-line output in a shell script

Tags:

linux

bash

shell

I'm trying to change the message of the day (MOTD) on my Ubuntu Amazon EC2 box so that it will display the git status of one of my directories when I SSH in.

The output from all of the default MOTD files have two spaces at the start of each line so it looks nicely indented, but because my git status output spans several lines, if I do echo -n " " before it only indents the first line.

Any idea how I can get it to indent every line?

like image 641
Matt Fletcher Avatar asked Jul 05 '13 08:07

Matt Fletcher


People also ask

How do you indent in shell 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.

How do you write a multiline string in a shell script?

Use Shell Variable to Make Multi-Line String in BashCopy greet="Hello > , > wolrd > !" The command below gets the multi-line string in the shell variable, greet , and redirects it to the specified file, multiline. txt , using > . Check the content of the multiline.

How do you echo multiple lines in shell?

To add multiple lines to a file with echo, use the -e option and separate each line with \n. When you use the -e option, it tells echo to evaluate backslash characters such as \n for new line. If you cat the file, you will realize that each entry is added on a new line immediately after the existing content.

How do I create a multiline string in bash?

Bash Escape Characters For example, if we have a multiline string in a script, we can use the \n character to create a new line where necessary. Executing the above script prints the strings in a new line where the \n character exists.


2 Answers

Pipe it to sed to insert 2 spaces at the beginning of each line.

git status | sed 's/^/  /' 
like image 131
Barmar Avatar answered Sep 20 '22 18:09

Barmar


Building on @Barmar's answer, this is a tidier way to do it:

indent() { sed 's/^/  /'; }  git status | indent other_command | indent 
like image 42
Marplesoft Avatar answered Sep 18 '22 18:09

Marplesoft