How to Print a Variable in Bash

This article will introduce how to print a variable in Bash.

1. echo

echo prints strings and variables to the screen.

1.1 Example

You can directly print a string or print a variable as follows.

#!/bin/bash

echo "Hello, world"

str="Hello, Bash"
echo $str

Output:

$ bash example.sh
Hello, world
Hello, Bash

1.2 Example

You can combine two strings and print them together like below.

#!/bin/bash

str1="Hello"
str2="Bash"

echo "str1=${str1}, str2=${str2}"

Output:

$ bash example.sh
str1=Hello, str2=Bash

2. printf

printf can be used to print strings to the screen using string formatting.

2.1 Example

You can print strings directly, like echo, or print a variable.

#!/bin/bash

printf "Hello, Bash\n"

str="Hello, Bash\n"
printf "$str"

Output:

$ bash example.sh
Hello, Bash
Hello, Bash

2.2 Example

printf supports string formatting and allows you to combine the contents of a variable with a certain format to output.

#!/bin/bash

str="Hello, Bash"

printf "{%s}\n" "$str"

Output:

$ bash example.sh
{Hello, Bash}

When the format takes two arguments, you can pass two variables as arguments. You can also use expressions such as \t(tab).

printf "[%s\t%s]\n" "First" "Second"

Output:

$ bash example.sh
[First	Second]

The format takes one variable, and if two or more variables are passed as arguments, a string is created and output for each argument.

#!/bin/bash

str="Hello, Bash"
str2="Hello printf"

printf "{%s}\n" "$str" "$str2" "Hello!"

Output:

$ bash example.sh
{Hello, Bash}
{Hello printf}
{Hello!}

Formats such as $.1f and $.2f are also supported to represent the number of decimal places of a float.

#!/bin/bash

printf "%.1f\n" 255 0xff 3.5

Output:

$ bash example.sh
255.0
255.0
3.5
codechachaCopyright ©2019 codechacha