Featured Post

Taking inputs from user in a script

Here we will see how to take input from user in a script with the help of read command. #!/bin/bash Lets try multiplication of two numbers which the user enters. What read does is ? It takes values by user on stdin. It prompt the user to input any value on stdin. -p is used to display a prompt. read -p "First number:" value1 This will give a prompt as " First number " and store the value in variable " value1 " echo Will display a blank line. read -p "Second number:" value2 This will give a prompt as " Second number " and store the value in variable " value2 " echo Will display a blank line. read -sn1 -p "Press any key to see the answer..." Just to make it bit more interactive lets add one more thing. -s means silent mode that is if any value is pressed it will not be displayed on the screen like as in the password. -nX means how many characters. X here is one that is any

Writing your first script

#!/bin/bash
  • First line of the script, lets divide it into pieces:
    • ! is ka she-bang
    • /bin location of bash
    • bash is an interpreter stored in /bin directory.
  • vim is a text editor that supports color coding, that will be really helpful.
  • A good script always have following things:
    • #Author
    • #Date
    • #Contact details
    • #Script usage
    • #Version history
  • Lets try a sample hello world script
    • echo "Hello World" 
      • Print this on stdout
  • echo command is used to print text to your standard output.
  • Add above line in a file called 1_simple_script.sh or any name of your choice.
  • Then we need to change its permission that is we need to get it an execute permission.
    • chmod u+x X.sh
      • If we will not add +x it will show permission denied.
  • There are various ways of executing a script some are given below:
[sunny@sunny-workstation bin]$ ~/bin/1_simple_script.sh
Hello World
[sunny@sunny-workstation bin]$ /home/sunny/bin/1_simple_script.sh
Hello World
[sunny@sunny-workstation bin]$ bash 1_simple_script.sh
Hello World
[sunny@sunny-workstation bin]$ ./1_simple_script.sh 
Hello World

Comments

Popular posts from this blog

Merging of various commands

Positional parameters in Bash scripting

Sourcing a variable