简体   繁体   中英

Unix Shell Scripts Functions

I'm learning to make little programs in Shell and I was looking how to define a function that uses the system calculator (bc -l). I will show what i'm trying to do:

#!/bin/bash
square (){
I need help here!
}
cube (){
I need help here!
}
rectangle (){
I need help here!
}
exit (){
help
}
I need help here!
echo "Little program that computes the following:"
echo "a) Surface of a square"
echo "b) Volume of a cube"
echo "c) Surface of a rectangle"
echo "e) exit"
echo "Choose the option you want to compute"
read answer
if [ $respuesta == "a" ]
then echo "What's the side of the square"
read l`

After that line i don't now how to calll my function that "eats" the user's answer and then display the computation. The things get worst because after the computation I have to ask the user if he wants to continue or exit. If anyone could help me, i will be very grateful. Sorry about my english. I'm not a native speaker.

Is this what you are looking for?:

menu="some items to choose from:
                A) something
                B) something else"
sample () {
    a="$1"
    b="$2"
    c="$3"
    printf "c: %s" "$c"
    echo "$a+$b" | bc
    echo "$a*$b"  | bc
    echo "$a/$b"  | bc
}

add=$(echo "2+2" | bc)
printf "Added: %s\n" "$add"

echo "$menu"
read -p "choose: " choice

case "$choice" in
    A) sample "30" "5";;
    B) sample "2" "2" "2";;
    *) echo "not a choice";;
esac

Here is the code which supported in BASH with select statement. For the function of square, cube, rectangle, you should be fine to finish it.

#!/usr/bin/env bash

square (){
echo "I need help here! - square"
}
cube (){
echo "I need help here! - cube"
}
rectangle (){
echo "I need help here! - rectangle"
}
exit (){
echo "help"
}

options=("Surface of a square" "Volume of a cube" "Surface of a rectangle" "exit")

select opt in "${options[@]}"
do
    case $opt in
        "${options[0]}")
            echo "you chose choice 1"
            square
            ;;
        "${options[1]}")
            echo "you chose choice 2"
            cube
            ;;
        "${options[2]}")
            echo "you chose choice 3"
            rectangle
            ;;
        "${options[3]}")
            break
            ;;
        *) echo invalid option;;
    esac
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM