如何在Bash Shell脚本中的字符串周围生成边框? [英] How to generate a border around a string in Bash shell script?

查看:119
本文介绍了如何在Bash Shell脚本中的字符串周围生成边框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以使用诸如- | 之类的字符在Bash中的给定字符串周围生成边界,并自动扩展到字符串的长度?给定的字符串不应包含EOF序列,应在处理后将其删除.

Is there a way to generate a border around a given string in Bash using characters like - and | and automatically expand to the length of the string? The given string should not include EOF sequences and be removed when processed.

echo "------------------"
echo "| External Drive |"
echo "------------------"

推荐答案

无需外部工具即可执行的小功能:

Little function that does it, without external tools:

border () {
    local str="$*"      # Put all arguments into single string
    local len=${#str}
    local i
    for (( i = 0; i < len + 4; ++i )); do
        printf '-'
    done
    printf "\n| $str |\n"
    for (( i = 0; i < len + 4; ++i )); do
        printf '-'
    done
    echo
}

例如,通过将其添加到您的 .bashrc 中将其来源,就可以不加引号将其调用:

Once this is sourced by, for example, adding it to your .bashrc, it can be called without quoting:

$ border multiple words
------------------
| multiple words |
------------------

这篇关于如何在Bash Shell脚本中的字符串周围生成边框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆