首页 > 解决方案 > 脚本输入所有条件

问题描述

我想编写一个带有 2 个参数的脚本,

例如:./manage_cc alpha 512

现在我编写了以下脚本,据说它涵盖了我的案例,但它似乎涉及所有条件。当然我的语法被破坏了,所以任何帮助都将不胜感激。

#!/bin/bash


echo -n $2 > /sys/module/tcp_tuner/parameters/$1

if [["$1" == ""] || ["$2" == ""]]
then
        echo "You need to pass a property to modify as a first parameter and a value as the second"
fi

if  [["$1" == "alpha"] || ["$1" == "beta"]]
then
        echo -n $2 > /sys/module/tcp_tuner/parameters/$1
else
        if [["$1" == "tcp_friendliness"] || ["$1" == "fast_convergence"]]
        then
                if [["$2" != "0"] && ["$2" != "1"]]
                then
                        echo "This parameter only accepts a boolean value (0/1)"
                        exit 1
                else
                        echo -n $2 > /sys/module/tcp_tuner/parameters/$1
                fi
        else
                echo "The only accepted values for first parameter are alpha/beta/tcp_friendliness/fast_convergence"
                exit 1
        fi
fi

标签: bashshell

解决方案


重写您的代码:

#!/usr/bin/env bash

write() {
    printf "%s" "$2" > "/sys/module/tcp_tuner/parameters/$1"
}

die() {
    echo "$*" >&2
    exit 1
}

main() {
    [[ -z $2 ]] && die "You need to pass a property to modify as a first parameter and a value as the second"

    case $1 in
        alpha|beta)
            write "$1" "$2"
            ;;
        tcp_friendliness|fast_convergence)
            if [[ "$2" == "0" || "$2" == "1" ]]; then
                write "$1" "$2"
            else
                die "This parameter only accepts a boolean value (0/1)"
            fi
            ;;
        *)  die "The only accepted values for first parameter are alpha/beta/tcp_friendliness/fast_convergence"
            ;;
    esac
}

main "$@"

推荐阅读