linux - Linux shell 脚本中的参数

标签 linux shell

我正在尝试在 Linux 中创建一个充当基本计算器的脚本文件。需要传递3个参数或者不传递参数。

如果有3个参数,应该可以这样执行。

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

但如果它没有任何参数,则应显示菜单,询问减法、加法或退出。

这个布局看起来怎么样?我一直在尝试,但每当我运行它时,它都会给我错误,说我需要输入参数,然后在错误之后显示菜单。

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

最佳答案

这是一个“可爱”的答案。稍后我会就您的代码向您提供一些反馈。

#!/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 <<< "$*")"
<小时/>

这里是重写,希望展示一些有用的技术和良好实践

#!/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
  • 使用函数实现模块化
  • 用于轻松扩展分支的 case 语句
  • select 语句生成菜单并强制输入有效
  • bash 的内置算术表达式
  • 使用“$@”传递参数
  • 在需要引用的地方引用变量

关于linux - Linux shell 脚本中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29524646/

相关文章:

c# - 是否可以通过 Silverlight 应用程序操作远程(在服务器上)xml/txt 数据库文件?

php - 是否有用于发送群发邮件(即时事通讯)的开源 PHP 软件?

linux - 一起使用 find、grep 和 sed

linux - "telnet"命令在 shell 脚本中执行时失败并显示 "bad port",但在命令提示符下有效

linux - 找到一个模式并替换它的一个字符

linux - 在 linux 中比较字符串变量

linux - 设置 Android Studio 的 GRADLE_HOME

bash - 如何将 MSYS2 shell 集成到 Windows 上的 Visual Studio 代码中?

linux - 为什么有一个 “integer expression expected” ?

linux - 如何在变量中搜索特定的一段文本?