Linux 在 shell 脚本中缩进多行输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17484774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:23:31  来源:igfitidea点击:

Indenting multi-line output in a shell script

linuxbashshell

提问by Matt Fletcher

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.

我正在尝试更改我的 Ubuntu Amazon EC2 盒子上的当天消息 (MOTD),以便在我通过 SSH 登录时显示我的一个目录的 git 状态。

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 statusoutput spans several lines, if I do echo -n " "before it only indents the first line.

所有默认 MOTD 文件的输出在每一行的开头都有两个空格,因此它看起来很好缩进,但是因为我的git status输出跨越多行,如果我echo -n " "在它之前这样做,它只会缩进第一行。

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

知道如何让它缩进每一行吗?

采纳答案by Barmar

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

用管道将sed其插入以在每行的开头插入 2 个空格。

git status | sed 's/^/  /'

回答by Marplesoft

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

基于@Barmar 的回答,这是一种更整洁的方法:

indent() { sed 's/^/  /'; }

git status | indent
other_command | indent

回答by Oliver Dungey

Thanks to @Barmar and @Marplesoft for some nice simple solutions - here is another variation that others might like - a function you can tell how many indent levels using pr:

感谢@Barmar 和@Marplesoft 提供了一些不错的简单解决方案-这是其他人可能喜欢的另一种变体-您可以使用一个函数来判断缩进级别pr

indent() {
  local indentSize=2
  local indent=1
  if [ -n "" ]; then indent=; fi
  pr -to $(($indent * $indentSize))
}

# Example usage
ls -al | indent
git status | indent 2