Thursday, October 1, 2009

Hash sign (#) in shell script

- With the exception of #! if the line is started by the hash sign then that line in shell script is considered as comment and hence that line is ignored during execution of shell script.

So, a simple example of shell script comment is,

# This line is considered as comment in shell script.


Note that if the first line of the shell script begins with #! then the script tells your system that this file is a set of commands to be fed to the command interpreter indicated and it is not a comment then which is discussed inside topic What is sharp-bang appear at first inside shell script.

- Comment can also appear at the end of the command provided that there is a whitespace before the hash. If there is no whitespace before the hash then comment becomes part of the command.
Following is an example.

$ cat comment_test.sh
echo "This is a comment"#comment

$ sh comment_test.sh
This is a comment#comment

$ cat comment_test.sh
echo "This is a comment" #comment

$ sh comment_test.sh
This is a comment

- Comment also allow whitespace before starting a line.

# This comment is preceded with tab


- Comment can also be embedded within a pipe.

var=( `cat "$filename" | sed -e '/#/d' | tr -d '\n' |\
# Delete lines containing '#' comment character.
sed -e 's/\./\. /g'` )


- In the same line after comment commands are not allowed. As in a line there is no way to terminate comment once it is started so any command after comment will be treated as comment. So for command we need to put it in the new line.

- Note that if hash sign appears within quotes (may be single quote ' or double quote ") or after escape characters ( that is after backslash \ ) then that is not considered as comment.

Also in case of parameter-substitution constructs and in numerical constant expressions. So if we write hash in the way of ${#*}, ${#@}, ${#var} or $(( 2#101 ))
then # is not considered as comment.

echo "The # does not begin a comment."
echo 'The # does not begin a comment.'
echo The \# does not begin a comment.
echo The # begins a comment here.

echo ${PAR#*:} # Parameter substitution, not a comment.
echo $(( 2#1010 )) # Base conversion, not a comment.


- In case of pattern matching operations like ${var/#Pattern/Replacement} (If prefix of var matches Pattern, then substitute Replacement for Pattern.) # is not considered as comment rather it is matched at prefix (beginning) of string.
Related Documents
1. Introduction -What is kernel, shell, shell script.
2. Basic Steps to write a shell script
3. Variables in shell script
4. Output text with echo command
5. Arithmetic operation and expression in shell script with expr
6. Basic shell programming commands quote, exit and read
7. Wildcard characters in linux
8. Assignment and comparison variable in shell script
9. Command writing, command line arguments in shell script
10. Input-Output rediection on linux
11. Pipe with example in linux


No comments:

Post a Comment