Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I align variables in a string with echo and bash?

I want to do formatting using echo in shell scripting.

Here is a small code snippet which is giving me the problem:

echo -en "\rFileName    :   $filename   :    $index of $lines Completed"

The $filename is a string with varying length, and this is causing problem with formatting in the terminal. How can I overcome this?

Here's what I mean:

FileName :       a800_102 :    6 of 6 Completed
FileName :       ersf_1024    :    56 of 56 Completed

I would like to have a table format when I display it on the terminal.

like image 569
Kiran Avatar asked Mar 03 '10 11:03

Kiran


People also ask

What is echo $$ in bash?

The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.

What does $_ mean in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.

How do I declare a string variable in bash?

To initialize a string, you directly start with the name of the variable followed by the assignment operator(=) and the actual value of the string enclosed in single or double quotes. Output: This simple example initializes a string and prints the value using the “$” operator.


1 Answers

Use printf:

printf "\rFileName : %20s : %8d of %8d Completed" $filename $index $lines
like image 86
richq Avatar answered Sep 18 '22 05:09

richq