简体   繁体   中英

Parameters in Linux shell script

I am trying to create a script file in Linux that acts as a basic calculator. It needs to pass 3 parameters or no parameters.

If it has 3 parameters, it should be able to execute like this.

./mycalc 1 + 2
the sum of 1 plus 2 equals 3

But if it does not have any parameters a menu should display asking for subtraction, addition, or exit.

How would this layout look? I keep trying but whenever I run it it gives me errors saying I need to enter the parameters and then after the error the menu displays.

op="$2"

if [ $op == "+" ]
then
   sum=$(expr $1 + $3)
   echo "The sum of $1 plus $3 equals $sum"
elif [ $op == "-" ]
then
   diff=$(expr $1 - $3)
   echo "The sum  of $1 minus $3 equals $diff"
else    

while [ $ch != "X" ] || [ $ch != "x" ] 
do
read -p "C) Calculation
 X) Exit" ch

Command line parameters are referenced as $1, $2, $3... ($1 for first arg, $2 for second ...)

you can test if parameters are not null with :

if [ -z "$1" ]
  then
    echo "No argument supplied"
fi

Here's a "cute" answer. I'll give you some feedback on your code later.

#!/bin/bash
case $2 in 
  +|-) :;; 
  *) echo "unknown operator: $2"; exit 1;;
esac
declare -A ops=( 
  ["-"]=minus 
  ["+"]=plus 
)
printf "%d %s %d equals %d\n" "$1" "${ops["$2"]}" "$3" "$(bc <<< "$*")"

Here's a rewrite, hopefully demonstrating a few useful techniques and good practices

#!/bin/bash

user_args () {
    case $2 in
        +) echo "The sum of $1 plus $3 equals $(( $1 + $3 ))" ;;
        -) echo "The sum of $1 minus $3 equals $(( $1 - $3 ))" ;;
        *) echo "I don't know what to do with operator '$2'" ;;
    esac
}

interactive () {
    PS3="Select an operator: "
    select choice in plus minus exit; do
        case $choice in
            plus)  operator="+"; break ;;
            minus) operator="-"; break ;;
            exit)  exit;;
        esac
    done
    read -p "First value: " first
    read -p "Second value: " second
    echo "The sum of $first $choice $second equals $(( $first $operator $second ))"
}

if (( $# == 3 )); then
    user_args "$@"
else
    interactive
fi
  • use of functions for modularity
  • case statement for easily expanded branching
  • select statement to generate the menu and enforce valid input
  • bash's built-in arithmetic expressions
  • passing arguments with "$@"
  • quoting variables everywhere the need to be quoted

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