Wednesday, 23 August 2017

Unix Shell Scripting Tutorial - page 1

Unix Shell Scripting Tutorial - Step 1

Question: How to create file shell script file?
echo "Hello World? How are you all?";



Question: How to make a file executable?
chmod a+rx script1.sh



Question: How to run execute file?
Just with name, you can execute.
script1.sh



Question: How to add comment in shell script files?
Use hash(#) before the line for comment.
chmod a+rx script1.sh



Question: How to use variable in shell script file?
name="Manoj"
echo "My Name is : $name"



Question: What is variable convention?
The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the underscore character ( _).


Question: How to define read only variable?
readonly version="10.2"
echo "Version is : $version"



Question: How to unset variable?
name="Manoj"
unset name;



Question: What are different type of variable?
  1. Local Variables: A local variable is a variable that is present within the current instance of the shell.
  2. Environment Variables: An environment variable is available to any child process of the shell. Some programs need environment variables in order to function correctly.
  3. Shell Variables: A shell variable is a special variable that is set by the shell.



Question: How to use Escape Characters?
Use slash \ for Escape the character;

echo "Hello \"User\""; // Hello "User"
echo "Slash \\" ;// Slash \



Question: How to use expression in shell script file?
Use expr enclosed with caret (~), For Example
myvar=10;
result=`expr 10 * 5`
echo "Multiple: $result";

myvar=10;
result=`expr 10 + 5`
echo "Additon: $result";

myvar=10;
result=`expr 10 -5`
echo "Subtract: $result";

Question: How to use loop?
for i in 1 2 3 4 5
do
  echo "Number $i"
done



Question: How to use if else condition?
if [ 2 = 3 ]
then
  echo "Both are equal"
else
  echo "Both are not equal"
fi



Question: How to use if else elseif condition?
if [ 2 = 3 ]
then
  echo "Both are equal"
elseif [ 2 > 3 ]
  echo "2 is greater than 3"
  else
  echo "2 is less than 3"
fi



Question: How to read from user?
echo "What is your name?"
read name
echo "Your name is $name"


Question: How to search a folder with name?
find ~ -type d -name "*foldername*" -print