Sé que los scripts de Shell solo ejecutan comandos como si se ejecutaran en el símbolo del sistema. Me gustaría poder ejecutar scripts de Shell como si fueran funciones ... Es decir, tomar un valor de entrada o una cadena en el script. ¿Cómo me acerco a hacer esto?
El comando Shell y los argumentos de ese comando aparecen como numerados Variables Shell: $0
Tiene el valor de cadena del comando en sí, algo así como script
, ./script
, /home/user/bin/script
O lo que sea. Cualquier argumento aparece como "$1"
, "$2"
, "$3"
Y así sucesivamente. El recuento de argumentos está en la variable Shell "$#"
.
Las formas comunes de tratar esto implican los comandos de Shell getopts
y shift
. getopts
se parece mucho a la función de biblioteca C getopt()
. shift
mueve el valor de $2
a $1
, $3
a $2
, y así sucesivamente; $#
Se decrementa. El código termina mirando el valor de "$1"
, Haciendo cosas usando un case
… esac
para decidir sobre una acción, y luego haciendo un shift
para mover $1
Al siguiente argumento. Solo tiene que examinar $1
, Y tal vez $#
.
Puede acceder a los argumentos pasados con $n
donde n
es el número de argumento - 1, 2, 3, ...
. Pasa los argumentos como lo haría con cualquier otro comando.
$ cat myscript
#!/bin/bash
echo "First arg: $1"
echo "Second arg: $2"
$ ./myscript hello world
First arg: hello
Second arg: world
En un script bash, personalmente me gusta usar el siguiente script para establecer parámetros:
#!/bin/bash
helpFunction()
{
echo ""
echo "Usage: $0 -a parameterA -b parameterB -c parameterC"
echo -e "\t-a Description of what is parameterA"
echo -e "\t-b Description of what is parameterB"
echo -e "\t-c Description of what is parameterC"
exit 1 # Exit script after printing help
}
while getopts "a:b:c:" opt
do
case "$opt" in
a ) parameterA="$OPTARG" ;;
b ) parameterB="$OPTARG" ;;
c ) parameterC="$OPTARG" ;;
? ) helpFunction ;; # Print helpFunction in case parameter is non-existent
esac
done
# Print helpFunction in case parameters are empty
if [ -z "$parameterA" ] || [ -z "$parameterB" ] || [ -z "$parameterC" ]
then
echo "Some or all of the parameters are empty";
helpFunction
fi
# Begin script in case all parameters are correct
echo "$parameterA"
echo "$parameterB"
echo "$parameterC"
Con esta estructura, no confiamos en el orden de los parámetros, ya que estamos definiendo una letra clave para cada uno de ellos. Además, la función de ayuda se imprimirá todas las veces que los parámetros se definan incorrectamente. Es muy útil cuando tenemos muchos scripts con diferentes parámetros para manejar. Funciona de la siguiente manera:
$ bash myscript -a "String A" -b "String B" -c "String C"
String A
String B
String C
$ bash myscript -a "String A" -c "String C" -b "String B"
String A
String B
String C
$ bash myscript -a "String A" -c "String C" -f "Non-existent parameter"
myscript: illegal option -- f
Usage: myscript -a parameterA -b parameterB -c parameterC
-a Description of what is parameterA
-b Description of what is parameterB
-c Description of what is parameterC
$ bash myscript -a "String A" -c "String C"
Some or all of the parameters are empty
Usage: myscript -a parameterA -b parameterB -c parameterC
-a Description of what is parameterA
-b Description of what is parameterB
-c Description of what is parameterC
$/shellscriptname.sh argument1 argument2 argument3
También puede pasar la salida de un script de Shell como argumento a otro script de Shell.
$/shellscriptname.sh "$(secondshellscriptname.sh)"
Dentro del script de Shell puede acceder a argumentos con números como $1
para el primer argumento y $2
para el segundo argumento y así sucesivamente.
La forma
$ ./script.sh "[email protected]"
es el más conveniente para argv
. El delimitador arg es un espacio en blanco, pero se puede cambiar. No recuerdo cómo fuera de lugar. Luego usa
$1, $2, shift, if [ $# -ne 3 ]
para controlar el flujo. No suelo abrazar getopts si un case ... esac
Será suficiente.
./myscript myargument
myargument
se convierte en $1
dentro myscript
.
En el script de Shell; se convierte en el nombre de la variable $ 1. La segunda palabra se convierte en el nombre de la variable $ 2 y así sucesivamente.
cat << 'EOF' > test
echo "First arg: $1"
echo "Second arg: $2"
echo "List of all arg: [email protected]"
EOF
sh test hello world
Puede encontrar más en el manual de Shell (sh) en http://heirloom.sourceforge.net/sh/sh.1.html
Si está familiarizado con Python argparse, y no le importa llamar python para analizar argumentos bash, use bash argparse ( https://github.com/mattbryson/bash-arg-parse ),
Vea la misma respuesta aquí: https://stackoverflow.com/questions/7069682/how-to-get-arguments-with-flags-in-bash-script/50181287#50181287
#!/bin/bash
echo "First arg: $1"
echo "Second arg: $2"
echo "Your First Argument was $1 & Second Argument was $2" 2> /dev/null
------------------------------------------------------------------------
./scriptname.sh value1 value2
Lo siguiente es mío:
#!/bin/bash
echo 'First arg:' $1
echo 'Second arg:' $2
El nombre de Shell es para_script.sh
Luego ejecútelo: ./para_script.sh hello world