Comments and Escape

Comments are the useful information that the developers provide to make the reader understand the source code.

There are two types of comments:

  1. Single-line comment
  2. Multi-line comment

Single-line comments:

A single-line comment starts with a hashtag symbol with no white spaces (#) and lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next line and continue the comment.

syntax:

#!/bin/bash
# this is a comment.

Multi-line comments

there are some tricky ways to do multi-line comments in shell script let me show you some tricks for the same

  • Use : ' to open and ' to close (make sure you have space between : and ')
#!/bin/bash
: '
This is
multiline comment
in shellscript
'
  • another method
#!/bin/bash
: <<'END_COMMENT'
This is
multiline comment
in shellscript
END_COMMENT

Escape

The escape () preceding a character tells the shell to interpret that character literally.

A non-quoted backslash () is the escape character. It preserves the literal value of the next character that follows, with the exception of <newline>.

If a <newline> pair appears, and the backslash is not itself quoted, the <newline> is treated as a line continuation (that is, it is removed from the input stream and effectively ignored).

This allows you to break very long commands / command sequences (piping and transforming output etc.) in scripts into multiple lines for readability.

#!/bin/bash
# owner: Gaurav
# purpose: print some echo commands
echo this is gaurav sharma # in line comment
echo 'this is our first                 shellscript' # one more comment
# this is an another comment in shell script.
# echo -e "\033[0;31m fail message # here" # this is one more comment
# echo -e "\033[0;32m success message #  here"
# echo -e "\033[0;33m warning message here"
echo "my
name
is
gaurav"

echo "
########### Script Starting ########
purpose: going to install nginx
####################################
"
# strong quotes.
echo 'my \
name \
is \
gaurav'   # Escape character \ taken literally because of strong quoting.

echo " my \
name \
is \
gaurav \
" # Newline escaped.
echo -e "this is gaurav \t saurav \t test name"
echo -e "this is gaurav \v saurav \v test name"
echo -e "this is gaurav \n saurav \n test name"

let's run the above script and see the output

┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./echo.sh
this is gaurav sharma
this is our first                 shellscript
 fail message # here
 success message #  here
 warning message here
my
name
is
gaurav


########### Script Starting ########
purpose: going to install nginx
####################################


 my name is gaurav
this is gaurav   saurav          test name
this is gaurav
                saurav
                        test name
this is gaurav
 saurav
 test name

Demo Video

Click Here for Demo Video