Sunday, October 4, 2009

Asterisk (*) in shell script and linux

- In the regular expression, asterisk (*) matches the preceding pattern element zero or more times. For example if we write xy*z then it matches xz, xyz, xyyz etc. However, bash itself cannot recognize Regular Expressions. Within linux and shell script different utilities like sed, awk recognize * as regular expression metacharacters.

- For general unix command like for "ls" command asterisk (*) is not used as standard regular expression. A process named globbing recognize and expand * which does not behave like regular expression. For example, in case of listing file by ls command asterisk does not match hidden file name or in another word does not match with filenames that start with a dot.

Example:

$ touch .test

$ ls *
b.txt google.doc hi

$ ls -a
. .. .test b.txt google.doc hi

Note that in the above example with "ls *" command the .test file is not appeared.

- In the context of arithmetic operations, the * denotes multiplication.
Example:

$ expr 18 \* 4
72

As * is special character so to make multiplication we need to escape it by backslash.

- A double asterisk (**) can represent the exponentiation operator in arithmetic operation.
Example:

$ let "a=6**3"

$ echo $a
216


- Another use of double asterisk (**) is to matches filenames and directories recursively.

Example:

echo "Using **"
for filename in **
do
echo "$filename"
done # Lists complete file tree, recursively.

No comments:

Post a Comment