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

Merging of various commands

Lets create a file with following content:

#!/bin/bash
echo "Value which is there in variable USER  is $USER"

  • What this above line will do, it will fetch the variable USER which is built-in.

echo -e "-e is used to add new line $USER.\n"

  • Adding -e will execute \n and will add a new line.

name=$USER

  • We also can assign the built-in variables to another variables as here value of $USER will be stored in name variable.

echo -e "Assigning value of USER variable to another variable $name \n"

shortname=$(cat /etc/passwd | grep "sunny" | awk -F ":" '{print $5}' | cut -d " " -f1)

  • Here we are merging various commands.
  • What above line will do is firstly it will cat the file /etc/passwd from that it will grep the line which has sunny.
    • sunny:x:1000:1000:Sunny Bhambhani:/home/sunny:/bin/bash
  • Then by the help of awk command it will get the 5th field which contains the full name of the user.
    • Sunny Bhambhani
  • Then by the help of cut command it will get the first name from the full name.
    • Sunny
  • Then this final value will be stored in a variable called shortname.

echo -e "Output after merging various commands is $shortname."

sunny@sunny-workstation bin]$ ./3_echo_merge_commands.sh 
Value which is there in variable USER  is sunny
-e is used to add new line sunny.

Assigning value of USER variable to another variable sunny 

Output after merging various commands is Sunny.
sunny@sunny-workstation bin]$ 


Comments

Popular posts from this blog

Positional parameters in Bash scripting

Sourcing a variable