Sunday, March 13, 2022

[SOLVED] Create dynamic table in bash

Issue

I have bash script which creates different users and password. The passwords and users are stored in variables.

    cat << EOT
+---------------------------------------+
| Linux Logins                          |
+---------------+-----------------------+
| User          | Password              |
+---------------+-----------------------+
| $test      | $testpw               |
+---------------+-----------------------+

EOT

The Problem with this is that depending on the length of the stored variables the table gets messed up like this:

+---------------------------------------+
| Linux Logins                          |
+---------------+-----------------------+
| User          | Password              |
+---------------+-----------------------+
| michael         | helolopk8712t76               |
+---------------+-----------------------+

This is because the tabs are hardcoded. How can I solve this in a different way? I know there is awk and column to do so. I want it dynamic as in mysql console if that is possible.


Solution

I think you mean to say that your problem is due to the fact that your tabs are not hardcoded. But tabs are not really flexible enough to do what you want. You could do:

cat << EOT            
+---------------------------------------+              
| Linux Logins                          |              
+---------------+-----------------------+              
| User          | Password              |              
+---------------+-----------------------+              
| $(printf %-14s "$test")| $(printf %-22s "$testpw")|          
+---------------+-----------------------+              

EOT


Answered By - William Pursell
Answer Checked By - Terry (WPSolving Volunteer)