Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a border around a string in Bash shell script?

Tags:

bash

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 "------------------"
like image 964
Quincy Glenn Avatar asked Jun 05 '26 01:06

Quincy Glenn


2 Answers

I found a solution on another Stack Exchange site which works using sed. It had different wording for the question.

border()
{
    title="| $1 |"
    edge=$(echo "$title" | sed 's/./-/g')
    echo "$edge"
    echo "$title"
    echo "$edge"
}

border "External Drive"

results

------------------
| External Drive |
------------------
like image 68
Quincy Glenn Avatar answered Jun 07 '26 09:06

Quincy Glenn


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| %s |\n' "$str"
    for ((i = 0; i < len + 4; ++i)); do
        printf '-'
    done
    echo
}

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

$ border multiple words
------------------
| multiple words |
------------------
like image 37
Benjamin W. Avatar answered Jun 07 '26 08:06

Benjamin W.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!