Читать книгу Kali Linux Penetration Testing Bible - Gus Khawaja - Страница 67
Printing to the Screen in Bash
ОглавлениеThere are two common ways to write into the terminal command‐line output using Bash scripting. The first simple method is to use the echo
command that we saw in the previous chapter (we include the text value inside single quotes or double quotes):
$echo 'message to print.'
The second method is the printf
command; this command is more flexible than the echo
command because it allows you to format the string that you want to print:
$printf 'message to print'
The previous formula is too simplified; in fact, printf
allows you to format strings as well (not just for printing; it's more than that). Let's look at an example: if we want to display the number of live hosts in a network, we can use the following pattern:
root@kali:~# printf "%s %d\n" "Number of live hosts:" 15 Number of live hosts: 15
Figure 2.1 Bash Scripting
Let's divide the command so you can understand what's going on:
%s : Means we're inserting a string (text) in this position
%d : Means we're adding a decimal (number) in this position
\n : Means that we want to go to a new line when the print is finished
Also, take note that we are using double quotes instead of single quotes. Double quotes will allow us to be more flexible with string manipulation than the single quotes. So, most of the time, we can use the double quotes for printf
(we rarely need to use the single quotes).
To format a string using the printf
command, you can use the following patterns:
%s : String (texts)
%d : Decimal (numbers)
%f : Floating‐point (including signed numbers)
%x : Hexadecimal
\n : New line
\r : Carriage return
\t : Horizontal tab