¿Cómo hacer una operación lógica OR para comparar números enteros en scripts de Shell?

Resuelto Strawberry asked hace 13 años • 8 respuestas

Estoy intentando hacer una verificación de condición simple, pero no parece funcionar.

Si $#es igual 0o mayor que 1entonces saluda.

Probé la siguiente sintaxis sin éxito:

if [ "$#" == 0 -o "$#" > 1 ] ; then
 echo "hello"
fi

if [ "$#" == 0 ] || [ "$#" > 1 ] ; then
 echo "hello"
fi
Strawberry avatar Nov 06 '10 08:11 Strawberry
Aceptado

Esto debería funcionar:

#!/bin/bash

if [ "$#" -eq 0 ] || [ "$#" -gt 1 ] ; then
    echo "hello"
fi

No estoy seguro de si esto es diferente en otros shells, pero si desea utilizar <, >, debe colocarlos entre paréntesis dobles, así:

if (("$#" > 1))
 ...
Coding District avatar Nov 06 '2010 02:11 Coding District

Este código me funciona:

#!/bin/sh

argc=$#
echo $argc
if [ $argc -eq 0 -o $argc -eq 1 ]; then
  echo "foo"
else
  echo "bar"
fi

No creo que sh admita "==". Utilice "=" para comparar cadenas y -eq para comparar entradas.

man test

para más detalles.

jbremnant avatar Nov 06 '2010 02:11 jbremnant

Si está utilizando el estado del código de salida de bash $? como variable, es mejor hacer esto:

if [ $? -eq 4 -o $? -eq 8 ] ; then  
   echo "..."
fi

Porque si lo haces:

if [ $? -eq 4 ] || [ $? -eq 8 ] ; then  

La parte izquierda del OR altera el $? variable, por lo que la parte derecha del OR no tiene el $? valor.

luca76 avatar May 11 '2015 09:05 luca76

A veces es necesario utilizar corchetes dobles; de lo contrario, aparece un error como si hubiera demasiados argumentos.

if [[ $OUTMERGE == *"fatal"* ]] || [[ $OUTMERGE == *"Aborting"* ]]
  then
fi
TechNikh avatar May 02 '2016 15:05 TechNikh