Omar Hussein
Omar Hussein

Reputation: 1147

Script enters all conditionals

I'd like to write a script that takes 2 parameters,

for example: ./manage_cc alpha 512

Now i've wrote the following script that supposedly covers my cases, but it seems to go into all the conditionals. surely my syntax is broken so any help would be appreciated.

#!/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

Upvotes: 1

Views: 46

Answers (2)

glenn jackman
glenn jackman

Reputation: 246799

A rewrite of your code:

#!/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 "$@"

Upvotes: 3

Barmar
Barmar

Reputation: 780889

Your condition syntax is wrong. When you start a condition with [[ you have to end it with ]], not just ]. They don't nest like parentheses.

if  [[ "$1" == "alpha" || "$1" == "beta" ]]

Upvotes: 1

Related Questions