Error: Too many arguments

1

I need to compare all the words that I pass as arguments between them, and say if they are the same or not:

#!/bin/bash
#Ejercicio_4
if [ $# -ne 6 ]
  then
        echo Número de argumentos incorrecto
  else
        if [ $1 == $2 == $3 == $4 == $5 == $6 ]

                then
                        echo Son iguales
                else
                        echo No todas las palabras son iguales
        fi
fi
    
asked by JuanjoMB98 29.12.2018 в 02:23
source

2 answers

0

No, your if sentence is not valid, you should do the following:

if [[ $1 == $2 && $1 == $3 && $1 == $4 && $1 == $5 && $1 == $6 ]];

Basically:

  • We compare each parameter with the first one using% logical_co_co ( and ), if all are true then all are equal.
  • Note that we use && instead of [[ , the double brackets are an improvement of Bash to the simple bracket, which among other things allows the use of logical operators.
answered by 29.12.2018 / 03:35
source
-1

The "Too many arguments" error is because the operator [ (synonymous with the other built-in of bash test ) is a binary or unary operator, that is, evaluates one or, at most, two elements with a comparison operation. And you're having more than two.

Something that occurs to me, to avoid a kind of redundancy, is

#!/bin/bash

main() {

    declare total_argumentos=$#

    [[ $total_argumentos -ne 6 ]] \
        && echo "Cantidad de argumetos incorrecta." \
        && exit 1    

    declare c_palabras_unicas=$(uniq <<< "$( tr ' ' '\n' <<< "$@" | sort )" | wc -l)
    declare mensaje="Repeticiones: $((total_argumentos - c_palabras_unicas))"
    mensaje="${mensaje}\nPalabras diferentes: $c_palabras_unicas"

    [[ $c_palabras_unicas -eq 1 ]] && mensaje="${mensaje}\nTodas las palabras son iguales."
    [[ $c_palabras_unicas -eq $total_argumentos ]] && mensaje="${mensaje}\nTodas las palabras son diferentes."

    printf "$mensaje\n" | column -t -s : 

}

main $@

Whose execution would give something similar.

$ ./script.sh uno uno uno uno uno uno  # Todas los argumentos tiene la cadena "uno".
Repeticiones                      5
Palabras diferentes               1
Todas las palabras son iguales.
$ ./script.sh uno uno uno uno uno dos  # Ahora tienen una cadena "dos".
Repeticiones          4
Palabras diferentes   2
$ ./script.sh uno dos uno dos uno dos  # Se intercalan repetidos.
Repeticiones          4
Palabras diferentes   2
$ ./script.sh {1..6}  # Los numeros del 1 al 6
Repeticiones                         0
Palabras diferentes                  6
Todas las palabras son diferentes.

In this way, sort orders the entered arguments.

    
answered by 29.12.2018 в 05:44