NOS 120 final 6-10

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

bash shell prefix

#!/bin/bash

Write a Perl script to display the line "Perl was developed by Larry Wall".

#!/usr/bin/perl # Program name: exercise1.pl print ("Perl was developed by Larry Wall\n");

Write a Perl program that contains a hash variable and displays the keys. The hash variable contains the following key and value combinations: Key Value 1 Martin 2 Hanson 3 Stephens 4 Rawlins

#!/usr/bin/perl # Program name: exercise10.pl %peoplelist = ('Martin', 1, 'Hanson', 2, 'Stephens', 3, 'Rawlins', 4); print ("The keys are:\n"); print ("$peoplelist{'Martin'}\n"); print ("$peoplelist{'Hanson'}\n"); print ("$peoplelist{'Stephens'}\n"); print ("$peoplelist{'Rawlins'}\n");

Write a Perl script in which you create a variable in the script to contain the name Beth and then have the script display "Welcome Beth."

#!/usr/bin/perl # Program name: exercise2.pl $name = "Beth"; print ("Welcome $name\n");

Modify the script you wrote in Exercise 2 so that you prompt for the name and then display "Welcome name".

#!/usr/bin/perl # Program name: exercise3.pl print ("Enter your first name: "); $name = <STDIN>; print ("Welcome $name\n");

Create a Perl program that uses an array of vegetables—peas, carrots, spinach, corn, beans—and in which all of the vegetables in the array are displayed to the screen.

#!/usr/bin/perl # Program name: exercise5.pl @vegetables = ("peas", "carrots", "spinach", "corn", "beans"); print ("The vegetables on my list are:\n"); print ("$vegetables[0]\n"); print ("$vegetables[1]\n"); print ("$vegetables[2]\n"); print ("$vegetables[3]\n"); print ("$vegetables[4]\n");

Write a Perl program that attempts to open a file that does not exist, and that prints the message "That file is nonexistent.".

#!/usr/bin/perl # Program name: exercise7.pl open (FILEIN, "nofile") || warn "Could not open students file\n";

Write a Perl program that converts a value in inches to a value in centimeters and displays the result. (1 inch = 2.54 centimeters.).

#!/usr/bin/perl # Program name: exercise8.pl print ("Enter a number of inches: "); $inches = <STDIN>; $cent = $inches * 2.54; print ("That is $cent centimeters\n");

Design a Perl program that sorts the last names Martin, Adams, Sandoval, Perry, Yablonsky, Brown, and Ramirez..

#!/usr/bin/perl #Program name: exercise6.pl @namelist = (Martin, Adams, Sandoval, Perry, Yablonsky, Brown, Ramirez); @sortednames = sort @namelist; print "@sortednames"; print"\n";

Create a C++ program that tests to see if the file accounts exists and prints a message to say whether the file exists.

#include <iostream> #include <fstream> using namespace std; int main(void) { ifstream file("accounts"); if (file.fail()) cout << "Can't find the accounts file.\n"; else { cout << "The accounts file exits.\n"; } }

Write a small C++ program that writes to the screen the make and model of the car or bicycle you own (or one that you wish to own)

#include <iostream> using namespace std; int main(void) { cout << "I own a Trek mountain bike.\n"; cout << "It was made in 2004.\n"; }

Create a program that enables you to input a positive integer and that will then tell you if it is a prime number or if it can be divided by 2.

#include <stdio.h> int main (void) { int num; int count; int signal; printf("Enter the number to test: "); scanf("%d", &num); for (count=2, signal=1; (count<=(num/2)) && signal; ) { if ((num % count) ==0) signal = 0; else count++; } if (signal) printf("%d is prime\n", num); else printf("%d has %d as a factor\n", num, count); }

Write a program in which a prompt asks for your first name and after you enter your first name the program displays it.

#include <stdio.h> int main() { char string[20]; printf("\nEnter your first name: "); scanf("%s", string); printf("Your first name is: %s\n", string); }

Modify the rain.c program you created in this chapter so that the total of all inches of rain when added together is 136 inches.

#include <stdio.h> int main() { int rain, total_rain = 0; for (rain = 0; rain < 17; rain++) { printf("We have had %d inches of rain.\n", rain); total_rain = total_rain + rain; } printf("We have had a total "); printf("of %d inches of rain.\n", total_rain); }

Write a C program called fedora.c that displays the line "Fedora is a version of Linux."

#include <stdio.h> int main() { printf("Fedora is a version of Linux.\n"); }

Write a program in which you enter a number and the program calculates and displays that number cubed.

#include <stdio.h> int main(void) { int num, cube; printf("\nEnter the number to cube: "); scanf("%d", &num); cube = num*num*num; printf("Your number cubed is: %d\n", cube); }

Rewrite the C program keyboard.c that you created earlier in this chapter to compile as a C++ program.

#include<iostream> using namespace std; int main(void) { char string[50]; float my_money; int weight; cout << "\nEnter your First Name: "; cin >> string; cout << "\nEnter your Desired Monthly Income: "; cin >> my_money; cout << "\nEnter your friend's weight: "; cin >> weight; cout << "\n\n Recap\n"; cout << "I am " << string; cout << " and I wish to have " << my_money; cout << " per month"; cout << "\nI never would have guessed your friend weighs " << weight; cout << "\n\n"; }

Create a program in which the user enters the outside temperature in Fahrenheit. If the temperature is 60 or over, print a comment that states "It is just fine outside." If the temperature is under 60, print a comment that states "It's not so warm outside."

#include<stdio.h> int main (void) { int temp; printf("\nEnter the outside temperature: "); scanf("%d", &temp); if (temp >=60) { printf("It is just fine outside.\n"); } else { printf("It's not so warm outside.\n"); } }

Write down four scalar variables, two of which are numeric and two that are strings.

$value = 45; $m = 90; $furniture = "desk"; $car = "Ford";

Create a shell variable that outputs the calendar for the current month.

CALNOW=`cal` CALNOW $CALNOW

How could you set up CALNOW so that it works every time you log in using the Bash shell?

Edit .bashrc or .bash_profile to contain the lines: CALNOW=`cal`

Create a Perl program that sorts the numbers 115, 10, 19, 35, and 2 and that uses the spaceship operator to accomplish the sort.

First create a data file, such as a file called numberlist that contains the numbers 115, 10, 19, 35, and 2 (with each number on a separate line). #!/usr/bin/perl # Program name: exercise9.pl $x = 0; while (<>) { $somelist[$x] = $_; $x++; } @sortedlist = sort numbers @somelist; print @sortedlist; sub numbers { $a <=> $b } chmod ./exercise9.pl numberlist

How can you set up your new whoisthere function so that it can be run each time you log in using the Bash script?

Switch to the home directory (cd and press Enter). Edit the .bashrc or .bash_profile login script to contain the line: . ~/source/them.

What are the exit statuses of the test command discussed in this chapter and what do they mean? How can you view the exit status results of the test command directly from the command line?

There are two exit statuses. Exit status 0 means true and exit status 1 means false. Type echo $? and press Enter to view the test command results

Use two different commands to display the contents of the HOME variable

Type printenv HOME and press Enter. Also, type echo $HOME and press Enter. echo ($) prints out a variable printenv views all variables, or single ones when specified

how shell scripts work

UNIX/Linux acts as an interpreter and compiles and executes in the same act

shell function

a group of commands stored in memory and assigned a name

dump [-options] devicename and partition or filename

backs up files and directories uses 9 levels, 0: all files 1: all files since last bu, 2: since all level 1, and so on

Set your shell from the command line to be the Bash shell. Then, use the echo command to verify the contents of the shell variable. What is now contained in the shell variable?

bash echo $SHELL

Make certain that your home directory is your current working directory. Use the command to verify that your source directory exists. How might knowledge of this command be useful when you create scripts for yourself or others?

cd test -d source echo $?

Make your home directory your current working directory. Use the vi or Emacs editor to open the veg_choice script you created in Chapter 6. Enter a line in that script to ensure the script uses the Bash shell. Run veg_choice to ensure your change works properly.

cd vi veg_choice #!/bin/bash >> insert at top

List the records in the corp_phones_bak file that you created earlier, so that they are displayed without colons separating the fields, but have one space between fields instead.

cd ~/source cat corp_phones_bak | tr ":" " "

Use a one line command to strip out the telephone prefix (219-) and the colons in the corp_phones_bak file and save the result in a file called noprefix?

cd ~/source cat corp_phones_bak | tr -d : | tr -d 219- > noprefix

Switch to your source directory and make a copy of the corp_phones file (which will give you a valuable backup of the corp_phones file) with the name corp_phones_bak. Using the tr command as a filter for output from another command, display to the screen the contents of corp_phones_bak so that all capitalized letters from A to M are lowercase.

cd ~/source cp corp_phones corp_phones_bak cat corp_phones_bak | tr [A-M] [a-m]

In your source directory, write a script called "them" in which you create a function called thethat displays a listing of who is logged in and displays the column headings for the information displayed.

cd ~/source vi them whoisthere() { who -H }

Edit the veg_choice script again, but this time change the line: if [ "$veg_name" = "carrots" ] to use the test command.

change the line to: if test $veg_name = "carrots" a

ispell [-options] filenames

checks spelling in files and suggests changes -b creates .bak -C ignores concatenated words -D orders suggest spelling from most to least likesly

Use the cmp command to compare the famous_words and famous_words.bak files.

cmp famous_words famous_words.bak

test -nt

compares first file in arg w second to see if first is newer

test -ot

compares first file in arg w second to see if first is older

cmp [-options] file1 file2

compares two files and indicates if they are different

test -eq

compares two integers to determine if they are equal

dd [option]

copies an input file and can convert the file's contents to another format or to have different characteristics

dd if

designates the input file

dd of

designates the output file

test -!

determines if an expression is fales

test -r

determines if file has read permission

test -w

determines if file has write permissions

test -x

determines if file is executable

test -s

determines if file is not empty

test stringa = stringb

determines if two strings are eyal

Use the df command to view file system use in megabytes.

df -m

uptime

displays how long the system has been up since the last boot

df [-options] [filesystems]

displays how space in a disk is allocated, used and free -h human readable -l only local -m size in mb -t only type of file system

After performing Exercise 3, use the test command to evaluate whether the shell variable contains a reference to the bash shell and use the echo command to determine the result. (Note that this provides one way to verify from within a script that the script user is set up to use the Bash shell.).

e test $SHELL = "/bin/bash" echo $?

mail [-options] [username]

enables you to send/get mail through computer or server

to reference a variable

enclose in {} or precede with $

Make the s variable you assigned in Exercise 2 an environment variable and use the command to verify it is recognized as an environment variable

export s printenv/ printenv s (shows that s is an env var)

Use the command that gives you information about swap space and memory use.

free

csh/tcsh

from C shell

Bash Shell

from bourne and korn

ksh/zsh

from korn shell

Save and test the revised phmenu.1 file using the groff and man programs.

groff -Tascii -man ./phmneu.1 | more man ./phmenu.1

Use the command that will enable you to view the documentation for ifconfig. Notice the many options for configuring your network connection.

ifconfig

Log in as root and try using ifconfig, netstat, and route. Also, when you use ifconfig, record the "inet addr" (IP) value for eth0 (your Ethernet address) or for lo (your localhost loopback address), such as 127.0.0.1 for lo.

ifconfig netstat route

Create a simple C program which declares the variable number as a local variable that is an integer.

int number; int main() { }

kill [PID]

kills a process can find PID w ps

test -a

logical AND

test -o

logical OR

test !

logical negation

Use a command to view the contents of the /etc/init.d directory to see a listing of services you can start on your computer. Do you see the portmap file

ls /etc/init.d

Run the man program with the argument df in the background. Record the PID of the process you have started.

man df&

Create a variable called mem_size and set its contents to 1024. Next, use the test command to determine if the contents of mem_size is less than or equal to 512.

mem_size=1024 test $mem_size -le 512 echo $?

top [options]

monitors CPU intensive stacks (doesn't need - for options) d: delay between screen updates p: monitors process w specified process id q: causes the top utility to refresh wo delay s: secure mode S: cumulative mode n: specifies how many times to update b: batch update (must also use w n) i: ignores any idle processes c: displays the command line instead of teh command name only

netstat [-options] host

monitors network traffic on host computer -a diplays stats for ports used by transport protocol -p shows programs in use related to active ports -n displays communications via ip and port numbers -s shows all stats

exit status (test)

numeric value that the command returns to the os when finished test: 0=true 1=false

let [expression with operators]

performs a given action on numbers that is specified by operators, and value is stored in a shell var PEMDAS

Find out the IP address of a friend's computer or of a favorite Web site and use the command to poll that computer or Web site.

ping [ip address]

If you are connected to a network, use the ping command to ping one or both of the addresses you obtained in Exercise 8. Also, if you have access to an Internet connection, use the ping command to ping the GNOME Web site, using ping gnome.com (or use another site provided by your instructor).

ping [ip address] ping 127.0.0.1 ping gnome.com

printenv [-option] [variable name]

prints a listing of environment and configuration variables specifies one or more vars as arguments to view info only about thos

ps [-options]

provides a listing of the currently running processes -A or -e shows all processes selected on the specified command na,e -p PID shows processes selected on the PID -l PID shows a long listing of information about processes l PID (longer than -l PID)

free [-options]

provides stats about free and used memory -b displays in bytes -m displays in mb -g in gb -s n continuous (ctrl c to end) -t creates totals for RAM and swap mem statistics

Log out of root and back in to your own account. Type the command to determine the PID of your Bash shell session and record the PID.

ps

Use the command to determine which users have processes running on your system.

ps -Au

restore [-options] device partition or filename

restores entire filesystems, specific files, and directories -f device or -file specifies device or file -i runs in interactive mode -N shows file names and directories on the backup medium -r restores a file system -x specifies certain files or directories to be restored

set -a set -n set -o, set -o noclobber set -u set -v

set -a: exports all vars after defined set -n: takes commands w/o executing them set-o: sets a particular shell mode set -o noclobber: prevents files from being overwritten by the > operator set -u: shows an error when there is an attempt to use an undefined operator set -v: displays command lines as they are they are executed

du [-options] [filesystem]

summarizes disk usage, with the default of presenting info by directory -a files and directories -b displays info in bytes -c creates a total at the end -h human readable -S omits size of subdirectories in totals for directories

Assign the variable t the value of 20. Next, assign the variable s the value of t+30. Finally, display the contents of t and s to verify you have correctly defined these variables.

t=20 let s=t+30 echo $t echo $s

test -e

tests existence of a file

test -d

tests for the existence of a specific directory

groff [-Tdev]

text formatting utility

Start the top utility. Type ? after the utility starts. What information do you see? Press Enter and stop the top utility.

top ? q

Start the top utility. Notice that top is listed as one of the most active processes. Determine what CPU percentage is used by running top. Stop the top utility.

top q

Start the top utility so that it updates every 20 seconds. Now do you see top in the list of the most active processes on your screen? Stop the top utility

top d 20 q

Use the touch command to create the file letters. Next use the dd command to make a backup of the file.

touch letters dd if=letters of=letters.bak

test [-options] [argument/expression/integer]

used to analyze an expression to see ifi its true, often used in shell scripts, to see if files exist

Use the vi editor to create and save the famous_words file with the following contents (including misspellings): Make a copy of the document using the dd command and calling the copy famous_words.bak. Use a tool to check and correct the spelling errors in the famous_words document.

vi famous_words dd if=famous_words of=famous_words.bak ispell famous_words

printenv

view list of current configuration(usually not changed) and environment (can be changed as needed) variables. You should to this before you change any

set [-options] [arguments]

w no options, displays the current listing of bash environment and shell script vars

Modify your whoisthere function so that you can enter "These are the folks logged in:" as an argument to appear before you list who is logged into the system.

whoisthere() { echo "$1" who -H }


Kaugnay na mga set ng pag-aaral

Chapter Eleven Psych Assignment Quizlet:

View Set

Ch. 13 Parents by Adoption and ART

View Set

WEEKS 3,4,5 QUIZ: INTRAPARTAL COMPLICATIONS, THERAPEUTIC MGT, BLEEDING DISORDERS, POSTPARTUM COMPLICATIONS

View Set

Chapter 44: Digestive and Gastrointestinal Treatment Modalities 1

View Set

Maternal Newborn Practice Questions

View Set