Hola, el siguiente script recibe como primer parámetro un archivo de texto y ordena las líneas de dicho archivo ascendentemente al pasarle una "A" como segundo parámetro o descendentemente al pasarle una "Z". Cuando lo ejecuto me sale esto: [: 16: missing ]
#!/bin/bash
if [ $# -ge 2 ]
then
if [ -f $1 ] && [ $2 = "A"]
then
`cat $1 | sort -d#`
else
if [ -f $1 ] && [ $2 = "Z" ]
then
`cat $1 | sort -r`
fi
fi
else
echo "Error: Falta pasar argumentos"
fi
El archivo de texto a ordenar es este:
ayer fui al estadio.
bonitas ideas las que tú tienes.
entro al segundo palo y gol.
Acabo de corregir un pequeño fallo, pero me da el siguiente error: script1: 16: ayer: not found#!/bin/bash
if [ $# -ge 2 ]
then
if [ -f $1 ] && [ $2 = "A" ]
then
`cat $1 | sort -d`
else
if [ -f $1 ] && [ $2 = "Z" ]
then
`cat $1 | sort -r`
fi
fi
else
echo "Error: Falta pasar argumentos"
fi
Me pregunto para qué utilizas `` si no te lo piden, es decir, no necesitas sustituir variables, solo ejecuta y ya, mira esto:
Tu script funciona bien así:
#!/bin/bash
if [ $# -ge 2 ]
then
if [ -f $1 ] && [ $2 = "A" ]
then
cat $1 | sort -d
else
if [ -f $1 ] && [ $2 = "Z" ]
then
cat $1 | sort -r
fi
fi
else
echo "Error: Falta pasar argumentos"
fi
leo@lein:~/Escritorio$ bash shell.sh file.txt A
ayer fui al estadio.
bonitas ideas las que tú tienes.
entro al segundo palo y gol.
leo@lein:~/Escritorio$ bash shell.sh file.txt Z
entro al segundo palo y gol.
bonitas ideas las que tú tienes.
ayer fui al estadio.
leo@lein:~/Escritorio$
Tenías razón, muchas gracias. Una pregunta al ejecutar un script ¿también se cuenta como parámetro el nombre del script?. Gracias.
No te entiendo qué quieres decir con eso de "se cuenta", explicame, por favor.
Se refiere a que si el contador "$#" tiene en cuenta el nombre del script.
Puedes comprobarlo facilmente...
if [ $# = 1 ]; then
echo "Lo cuenta"
fi
Y lo ejecutas sin paso de parametros: "sh prueba.sh".
Edito: Si se tiene en cuenta, es la variable $0.
Pues NO, no lo tiene en cuenta:
leo@lein:~/Escritorio$ cat shell.sh
#!/usr/bin/bash
echo -e "$#";
leo@lein:~/Escritorio$ bash shell.sh
0
leo@lein:~/Escritorio$
Como argumento posicional el mismo archivo ($0) no es tomado en cuenta.