bash 在bash中从占据终端全宽的破折号字符绘制一条水平线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42762643/
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-09-18 15:52:42  来源:igfitidea点击:

Draw a horizontal line from dash character occupying the full width of a terminal in bash

linuxbashterminal

提问by exebook

I need a command that will draw a horizontal "line" in the terminal. The line must be exactly the width of the terminal long (regardless of a current terminal width) and consist of a dash character (although a unicode symbol for a horizontal line can be also used).

我需要一个命令来在终端中绘制一条水平“线”。该线必须与终端的宽度完全相同(无论当前终端宽度如何)并且由一个破折号组成(尽管也可以使用水平线的 unicode 符号)。

It is better if it can be colored.

如果能上色就更好了。

I need to use it like this:

我需要像这样使用它:

echo some text
drawline
echo more text

And the output would look something like this:

输出看起来像这样:

echo some text
---------------------------------------------------------------------------------
echo more text

回答by Zumo de Vidrio

Try with:

尝试:

echo some text
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
echo some text

回答by cb0

In bash and zsh there is the $COLUMNSvariable which you can use.

在 bash 和 zsh 中有$COLUMNS您可以使用的变量。

I use this line for that purpose:

我为此目的使用这一行:

printf %"$COLUMNS"s |tr " " "-"

You can also use seq, but this is not as intuitive as the other solution:

您也可以使用seq,但这不如其他解决方案直观:

seq -s- $COLUMNS|tr -d '[:digit:]'

Edit:

编辑:

It seems that $COLUMNSis a local bash variable and you will need to export it. So now there are (at least) 2 options.

这似乎$COLUMNS是一个本地 bash 变量,您需要将其导出。所以现在有(至少)2 个选项。

  1. Export the variable before you call the script:

    export COLUMNS; ./your_script.sh
    
  2. Use tputas Zumo de Vidrio suggests.

    printf %"$(tput cols)"s |tr " " "-"
    
  1. 在调用脚本之前导出变量:

    export COLUMNS; ./your_script.sh
    
  2. 使用tput如谟德Vidrio建议。

    printf %"$(tput cols)"s |tr " " "-"
    

回答by Shakiba Moshiri

A simple Perl one-liner
stty size | perl -ale 'print "-"x$F[1]'

一个简单的 Perl 单行
stty size | perl -ale 'print "-"x$F[1]'



NOTE
you can see the heightand widthof your terminal with stty size

注意
你可以看到终端的高度宽度stty size



enter image description here

在此处输入图片说明

回答by Inoperable

Super simple horizontal ruler:

超级简单的水平尺:

repeat $(tput cols) echo -ne "-";

repeat $(tput cols) echo -ne "-";