Monday, 28 August 2017

Unix Shell Scripting Tutorial - page 3

Unix Shell Scripting Tutorial - page 3

Question: What are special variable in unix?
Special variable are those variable which are reserved by unix shell. For Example $$ is special variable and it return the current process id.


Question: How to use array variable in for loop?
Yes, we can define.
NUMS="1 2 3 4 5 6 7 8 9"
for NUM in $NUMS
do
   Q=`expr $NUM % 2`
   if [ $Q -eq 0 ]
   then
      echo "Number is an even number!!"
      continue
   fi
   echo "Found odd number"
done



Question: Give example of while with break?
a=2
while [ $a -lt 10 ]
do
   echo $a
   if [ $a -eq 5 ]
   then
      break
   fi
   a=`expr $a + 1`
done

Once $a will reach to 5, then it will break the statement.
output
2
3
4
5



Question: How to print the special character as string?
Use the Backslash before the special character, It will print. For Example:
echo \$;



Question: What is Output Redirection?
We use > notation to Output Redirection.
who > users
If a command has its output redirected to a file and the file already contains some data, that data will be lost.

We can use >> to append in file, it will not lost the data.
who >> users


Question: What are the Redirection Commands?
  1. pgm > file: Output of pgm is redirected to file.
  2. pgm < file: Program pgm reads its input from file.
  3. pgm >> file: Output of pgm is appended to file.
  4. n > file: Output from stream with descriptor n redirected to file
  5. n >> file: Output from stream with descriptor n appended to file
  6. n >& m: Merges output from stream n with stream m.



Question: How to create a custom function?
# Create a new function with name of Hello
Hello () {
   echo "Hello World! How are you?"
}

# Call the function
Hello



Question: How to create a custom function with parameter?
# Define your function here
Hello () {
   echo "Hello World! How are you?"
   echo "First parameter: $1";
   echo "Second parameter: $2";    
}

# Invoke your function
Hello first second

Output
Hello World! How are you?
First parameter: first
Second parameter: second