Question

In: Computer Science

Lab 3-5: Activity 5-5:  Using Condition Statements                                &nb

Lab 3-5:

Activity 5-5:  Using Condition Statements                                   10 minutes

Objective: Create a script with if, then, and else statements.

Description: In this activity, you create a shell script that tests whether a file the user specifies exists and uses output and error redirection to do some simple command validation.

NOTE:

If necessary, start a virtual machine in the server mode, and sign-on. This script will determine if a user has sudo permission and then as such can execute the find command and traverse the hierarchy without Permission denied errors.

Make a subdirectory in your home directory and call it scripts (for roots scripts).

  1. Using vim, create an empty file named scr5.
  2. Switch to extended mode and display the line numbers.
  3. Switch to insert mode, and then create a script that performs the following:
  4. Sets the environment for the script to bash
  5. Documents the following:This script will find a file and display its absolute path on the screen.
  6. Informs the user that this is a script that :
    1. This script is for the sudo users only!
    2. AND if the test for sudo access is successful.
  7. Test the users sign on to make sure they have sudo access.
  8. THEN:
  9. Clears the screen.
  10. Prompts the user for the file-name to be searched for
  11. Sets the reply in a meaningful variable.
  12. Uses the find command to find the file and redirects the output of the find command to a file and any errors to a separate error_file.
  13. Return to your scripts directory.
  14. Create an if-then-else construct that:
    1. Tests if the file exists and has data in it.
    2. If true, inform the user that the file was found AND Where the file is located.
    3. If false, inform the user that the file was not found AND to try again.
    4. Insures the user is placed in the scripts directory when the script ends

Exit insert mode and switch to extended mode.  Save your changes and exit the vimeditor.

Give the owner execute permission to run the script.  Run the script searching for a valid file, like bash.  

What command did you use to run the script?

Answer:____________________________

Explain how you would test the script to make sure it was working.

Answer:___________________________________________

Solutions

Expert Solution

(a)

bash script.sh

(b) An if statement is a kind of switch; if something is true, then you'll do one thing, and if it's false, you'll do something different. This if-then instruction is exactly the kind of binary decision making computers are best at; all you have to do is define for the computer what needs to be true or false and what to do as a result.

The easiest way you test for True or False is the test utility. You don't call it directly, you use its syntax. Try this in a terminal:

$ if [ 1 == 1 ]; then echo "yes, true, affirmative"; fi
yes, true, affirmative
$ if [ 1 == 123 ]; then echo "yes, true, affirmative"; fi

That's how test works. You have all manner of shorthand to choose from, and the one you'll use is the -z option, which detects if the length of a string of characters is zero (0). The idea translates in your despace script as:

#!/bin/sh

if [ -z "$1" ]; then
echo "Provide a \"file name\", using quotes to nullify the space."
exit 1
fi

mv "$1" `ls "$1" | tr -d ' '`

The if statement is broken into separate lines for readability, but the concept remains: if the data inside the $1 variable is empty (zero characters are present), then print an error statement.

Try it:

$ ./despace
Provide a "file name", using quotes to nullify the space.
$

Notice the statement exit 1. This is a way for POSIX applications to send an alert to the system that it has encountered an error. This capability is important for yourself and for other people who may want to use despace in scripts that depend on despace succeeding in order for everything else to happen correctly.

The final improvement is to add something to protect the user from overwriting files accidentally. Ideally, you'd pass this option through to the script so that it's optional, but for the sake of simplicity, you'll hard code it. The -i option tells mv to ask for permission before overwriting a file that already exists:

#!/bin/sh

if [ -z "$1" ]; then
echo "Provide a \"file name\", using quotes to nullify the space."
exit 1
fi

mv -i "$1" `ls "$1" | tr -d ' '`


Related Solutions

5.         Question 5                               &nb
5.         Question 5                                                                                                [Total: 20 marks] The spot price of silver is $50 per ounce. The storage costs are $ 0.52 per ounce to be paid at the end of the year. The futures contract on silver has 1 year and 6 months to maturity and the risk-free rate of interest is 0.9% per year with continuous compounding. What is the futures price (per ounce) if silver is considered to be an investment asset?  (Please display all computations.)                                                                    [10 marks]                                                                                                         Please define...
3.         Question 3                               &nb
3.         Question 3                                                                                                      [Total: 20 marks] Assume a futures contract with 8 months to maturity is employed to hedge a well-diversified portfolio over the next 6 months.  The contract size of one futures contract is $250 times the index (i.e. the futures on the index). The value of the S&P500 index is currently 1200. The current futures price is $1220. The value of the portfolio that you are hedging is $ 40 million. The Beta of the portfolio is 1.25. The risk-free rate...
Progression Chart View Lab Results  L.B.                                   &nb
Progression Chart View Lab Results  L.B.                                                                      J.B. Progesterone low                                             Testosterone Normal Estradiol normal                                                LH normal FSH normal                                                         TSH norm TSH normal                                                         Seminal parameters normal Pelvic ultrasound normal  J.B.'s semen analysis reveals no apparent problem. L.B. appears to be ovulating normally. BBT charting captures a change in temperature, and ovulation testing reveals an LH surge. The provider suspects L.B. may have a luteal phase defect because her progesterone levels are low after ovulation. The provider decides to order an hysterosalpingogram (HSG) for LB. How...
Question 3                                          &nb
Question 3                                                                                  (Total: 25 marks) Sikawan Systems manufactures two products in its Sabah division. Traditionally the company has used an overhead absorption system based on machine hours. However, following a management consultancy exercise in which outside consultants reviewed the management information systems, the directors have decided to pilot an Activity Based Costing system at the Sabah division. For the coming year, 2021, Sabah’s production overheads are estimated as follows: RM Factory rent and rates 42,200 Heat and...
Question – 3                                        &nb
Question – 3                                                                                                     30 Marks Plastic Manufacturing Company: Plastic Manufacturing Company manufactures Plastic Cartons. The Competition in the plastic industry is increasing. The production manager of the company is suggesting using standard costing system. He explains “Standard costing is a control technique where actual and standard costs and revenues are compared to obtain the variances and are used as an important tool to improve the performance” The company has the following standard cost card to manufacture each plastic carton. Direct...
Let 3x3 matrix A = -3 0 -4                               0 5 0        &nb
Let 3x3 matrix A = -3 0 -4                               0 5 0                              -4 0 3 a) Find the eigenvalues of A and list their multiplicities. b) Find a basis, Bi, for each eigenspace, E(i). c) If possible, diagonalise matrix A. (i.e find matrices P and D such that Pinv AP = D is diagonal).
Lab Activity for Mitosis and Meosis You are to create a 3-D model of Mitosis and...
Lab Activity for Mitosis and Meosis You are to create a 3-D model of Mitosis and Meiosis I and Meiosis II. You may use any materials you choose to create your models. Take pictures of your models and submit those pictures of your models. Also, please make sure that you send by way of assignment link, a copy of the descriptions of the stages, the materials used to denote the structures and what the structures represent.
3. Right to Cure.                                        &nb
3. Right to Cure.                                             FACTS: Metro-North Commuter Railroad Co. decided to install a fall-protection system for elevated walkways, roof areas, and interior catwalks in Grand Central Terminal, in New York City. The system was needed to ensure the safety of Metro-North employees when they worked at great heights on the interior and exterior of the terminal. Sinco, Inc., proposed a system called “Sayflida,” which involved a harness worn by the worker, a network of cables, and metal clips or...
Activity Predecessor Activity Duration in Weeks A ---- 3 B A 5 C A 7 D...
Activity Predecessor Activity Duration in Weeks A ---- 3 B A 5 C A 7 D B 10 E C 5 F D, E 4 Using the Critical Path Method (CPM), find the critical part, activities, and the date to finish the project (Gantt Chart would help). I would really appreciate excel screenshots!
22.8 LAB 5 D FALL 19 : Using math functions This lab problem demonstrates the use...
22.8 LAB 5 D FALL 19 : Using math functions This lab problem demonstrates the use of import module. The Python programming language has many strengths, but one of its best is the availability to use many existing modules for various tasks, and you do not need to be an experienced computer programmer to start using these modules. We have given you some incomplete code; note that the very first line of that code contains an import statement as follows:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT