Contact us |
Using Variables in scriptsExercise 3Using Variables in scriptsVariables are like "storage areas" to hold values. You will want to create variables for many reasons. You will need it to hold user input, arguments, or numerical values. You will write a script that accepts 2 numbers from the user and outputs the result of the addition of the 2 numbers. There are two variables used in the script below and they are being used to hold user input. 1. Make sure you are still in the myscripts directory. 2. Launch your text editor again and type in the following commands. (Line numbers have been included in sample below to aid readability. You shouldn’t include the line numbers in your own script) 1. #!/bin/bash 2. #this script will perform a simple addition 3. 4. first_num=0 5. second_num=0 6. 7. echo "Please type in the first number " 8. read first_num 9. 10. echo "Please type in the second number " 11. read second_num 12. 13. echo "$first_num plus $second_num equals $first_num + second_num " Lines 4 and 5 in the code above are declaring and initializing the variables (first_num and second_num). In shell scripting you don’t have to declare or initialize variable. Just mentioning a variable creates it. The “read” command in lines 8 and 11 will store whatever the user types into "first_num and second_num" respectively. 3. Save the code you typed in a file and call it “calc.sh” 4. Change the permissions on the file you created to make it executable. Type [root@localhost myscripts]# chmod u+x calc.sh 5. Run the script by typing: [root@localhost myscripts]# . calc.sh Write a very short script that asks for a person’s first name and stores it in a variable called “first_name”and prints out a personalized greeting with the person’s name?
|
Login... |