Tuesday, October 6, 2009

Paranthesis () in shell script

Parenthesis () within commands inside shell script indicates the list of commands as a command group.

A listing of commands inside shell script start a subsell. Variables within subshell is not visible from rest of the script. Within subshell main shell variables can be visible but the parent process which means the script cannot read variables created in the child process, the subshell.

Example:

$ cat >subshell.sh
var=10
(echo $var; var=11 ; echo $var)
echo $var

$ sh subshell.sh
10
11
10

From the example we see within subshell the value of variable var is changed but that value is not affected within main shell. And the variable of main shell can be accessed by the subshell.

- Parenthesis is used for array declaration.

$ cat >array_shell.sh
array_var=(one two three)
for (( i = 0 ; i < ${#array_var[@]} ; i++ ))
do echo ${array_var[$i]}
done

$ sh array_shell.sh
one two three


In this example, the value ${#array_var[@]} evaluates into the number of elements in the array (3 in this case). The individual elements of the array are accessed, one at a time, using the index integer $i as ${array_var[$i]}

Dollar sign ($) in shell script

- The dollar sign is used for variable substitution which means the value of a variable.

$ cat >var_example.sh
var="This is variable"
variable2=10
echo $var
echo $variable2

$ sh var_example.sh
This is variable
10

With preceding dollar sign $ variable name indicates the value the variable holds.

- In case of regular expression, dollar sign ($) means it matches ending position of a line or ending position of a string. A list of metacharacters are defined in http://arjudba.blogspot.com/2009/07/list-of-metacharacters-in-regular.html

- ${} is used for parameter substitution. ${var} is same as $var but comes with less ambiguity.
Example:

$ cat >par_subs
var=test
echo "This is ${var}-example."
echo This is $var-example.

$ sh par_subs
This is test-example.
This is test-example.

- With $* all of the positional parameters, can be seen as a single word. Positional parameters mean the parameter that we pass from command line to a script, passed to a function, or set to a variable. Note that, "$*" must be quoted.

- With $@ we can access positional parameter but each parameter is a quoted string. The parameters are passed on intact, without interpretation or expansion.
This means that each parameter in the argument list is seen as a separate word.

Example of both $* and $@:

$ cat >example_of_dollars.sh
#Check whether user has passed any arguments while running the script.
#;If first argument is NULL and does not exist then show echo about usage and quit.
if [ ! -n "$1" ]
then
echo "Usage: `basename $0` argument1 argument2 etc."
exit 3
fi

index=1 # Initialize index count to 1.

echo "Listing arguments with \"\$*\":" # Escape character \ is used to escape $ and "
for arg in "$*" # Note that "$*" doesn't work properly if "$*" isn't quoted.
do
echo "Argument #$index = $arg"
let "index+=1"
done # $* sees all arguments as single word.
echo "Entire arguments list seen as single word."

index=1 # Reset index count.

echo "Listing arguments with \"\$@\":" # Escape character \ is used to escape $ and "
for arg in "$@" # Note that "$@" is within double quote.
do
echo "Argument #$index = $arg"
let "index+=1"
done # $@ sees arguments as separate words.
echo "Argument list seen as separate words."
echo

index=1 # Reset index count.

echo "Listing arguments with \$* (unquoted):"
for arg in $*
do
echo "Argument #$index = $arg"
let "index+=1"
done # Unquoted $* sees arguments as separate words.
echo "Argument list seen as separate words."

exit 0


$ sh example_of_dollars.sh
Usage: example_of_dollars.sh argument1 argument2 etc.

$ sh example_of_dollars.sh test1 test2
Listing arguments with "$*":
Argument #1 = test1 test2
Entire arguments list seen as single word.
Listing arguments with "$@":
Argument #1 = test1
Argument #2 = test2
Argument list seen as separate words.

Listing arguments with $* (unquoted):
Argument #1 = test1
Argument #2 = test2
Argument list seen as separate words.


- With $? it is checked exit status of a command, a function, or of the script itself.
Example:

$ ls nofile_here
ls: cannot access nofile_here: No such file or directory

$ echo $?
2

$ ls welcome.sh
welcome.sh

$ echo $?
0


- The $$ variable holds the process ID of the script in which it appears.

Sunday, October 4, 2009

Question mark (?) in linux and shell script

- The question mark (?) in linux and shell script can be used to indicate a test for a condition. Within double parenthesis construct it can serve as an element of a trinary operator.
Example:

$ cat >question_ex.sh
var1=10
(( var2 = var1<20?0:100 ))
echo $var2

$ sh question_ex.sh
0


The command performing test operation by (( var2 = var1<20?0:100 ))
is same as,

# if [ "$var1" -lt 20 ]
# then
# var2=0
# else
# var2=100
# fi


- In a parameter substitution expression, the question mark (?) tests whether a variable has been set.
If we use following syntax,
${parameter?err_msg}, ${parameter:?err_msg}
then if parameter is set, then it's value is used, else it prints err_msg.


$ echo ${var?The variable is not set}
bash: var: The variable is not set

$ echo ${USER?The variable is not set}
Arju

In the above example in first case variable var is not set, hence error message appeared while in the second case variable USER is set and hence displays it's value.

- In case of pattern matching question mark (?) matches the preceding pattern element zero or one time. For example if we write xy?z then it matches only xz and xyz which is described in http://arjudba.blogspot.com/2009/07/list-of-metacharacters-in-regular.html. Note that with "?" filename expansion in globbing does not behave exactly like regular expression while in case of utility like sed/awk it behaves like regular expression.

10 Bangladesh Chhatra League (BCL) members rape a school girl

Before the http://arjudba.blogspot.com/2009/10/shame-on-bangladesh-girl-raped-by-bal.html here is the another pathetic history in Bangladesh performed by ten activitists of the current ruling party members.

Ten activists of Bangladesh Chhatra League (BCL) allegedly gang-raped a teenage girl Friday night and were later handed down mere punishment at village arbitration arranged to ensure their escape by local Awami League leaders.

Family sources say the AL leaders compelled the victim's father not to go for legal action and also took their signatures on three blank sheets to stop any future move to that end.

Police also released two of the accused held on the spot while handing the victim over to her father early Saturday morning.

A band of 16 youths kidnapped the girl, a class VII student of Pakhimara in Kalapara upazila, Friday night when she was returning home on a rickshaw from a Puja mandap with her cousin Nasir Uddin.
The BCL men beat up Nasir, drove him away and took the girl to a nearby garden. Ten of them raped the girl until her relatives with police rushed to the scene to rescue her around 2:00am.

Sub-inspector Kabir Hossain of Kalapara police station held two of the culprits -- Rajib and Sohag -- from the spot but freed them later after handing over the girl to her family.

Later on Sunday, local AL leaders including Kalapara upazila unit Secretary Rakibul Ahsan and Upazila Parishad Vice-Chairman Sultan Mahmud arranged the arbitration at Kalapara Girls' School in the evening.
The village arbitration in a farcical judgement fined all the 16 Tk 10,000 each and that they all be whipped 100 times each. Shame!

But four days into the grisly incident the victim's father, a poor farmer, still does not dare to file a case.
He said, "Rakibul (AL leader) and his men took signatures of me and my daughter on three blank sheets asking us not to seek justice anywhere else."

Rakibul Ahsan denied the allegation. He claims, "The youths did not rape the girl, they just made an attempt. We punished them so that they don't indulge into such activities in future."
The Kalapara AL leader also denied their political identity as BCL activists dubbing them as "spoilt brats".
Contacted, Kalapara police Officer-in-Charge (OC) Ishaq Ali said they released Rajib and Sohag as the victim's father did not file any complaint.

He says he does not know anything about the village arbitration, adding the police would not file any case of their own and "take legal steps if any complaint is filed".

The gang members were identified as Rajib, Rubel, Ratul, Pobitra, Mojibur, Omer, Rana, Sohel, Regan, Lalu, Jewel, Sohag, Bappi of Nayapara, Saiful and Munim of Madrasa Road in Kalapara upazila town and Al-Amin of Dhankhali.

Now a days this is becoming common scenarios by the ruling government party and their units.

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.