What does this syntax mean?
$ type echo
echo is a shell builtin
meaning, the echo
command is part of the bash
program itself (assuming you use bash)
-n
is an option, so let's see what it does
$ help echo
Write arguments to the standard output
...
-n do not append a newline
So when we run the line:
zanna@monster:~$ echo -n "Today's date is: "
Today's date is: zanna@monster:~$
Hmm that doesn't look very good, because there's no newline after the printed text. We'll come back to this.
$ type date
date is /bin/date
ah so the date
command is a separate program. What does it do?
$ man date
Display the current time in the given FORMAT, or set the system date.
The characters after the date
command are format options (which must be preceded by +
) - different parts of the date are specified (for example %A
is the full name of the day of the week - see the rest of man date
for the complete list of options)
$ date +"%A, %B %-d, %Y"
Tuesday, February 7, 2017
So if we put the commands together in a script and then run the script we will get
Today's date is: Tuesday, February 7, 2017
Nice! If you want the same effect in a terminal, you can use a semicolon to separate the two commands instead of a newline:
$ echo -n "Today's date is: " ; date +"%A, %B %-d, %Y"
Today's date is: Tuesday, February 7, 2017
You should start with manual pages, the command man
. Just type man <command>
to get information about a <command>
. Navigating in man
is not very intuitive but there are lots of guides to it, for example https://wiki.gentoo.org/wiki/Man_page/Navigate#Navigating_and_searching_man_pages.
Relevant parts of man echo
and man date
:
echo
echo [SHORT-OPTION]... [STRING]...
Echo the STRING(s) to standard output.
-n do not output the trailing newline
So it prints the string and does not go to the new line after that (which is the default behavior), so the output of the next command will be printed on the right side of the echoed string.
date
date [OPTION]... [+FORMAT]
FORMAT controls the output. Interpreted sequences are:
%A locale's full weekday name (e.g., Sunday)
%B locale's full month name (e.g., January)
%d day of month (e.g., 01)
%Y year
By default, date pads numeric fields with zeroes. The following optional flags may follow '%':
- (hyphen) do not pad the field
I hope it’s clear. Feel free to ask if not.