Por favor, mire este ejemplo de código:
MIN=10 if [ -n "$1" ]; then echo "$1"; fi if [ -n "$2" ]; then echo "$2"; fi if [ -n "$3" ]; then echo "$3"; fi if [ -n "$4" ]; then echo "$4"; fi if [ -n "$5" ]; then echo "$5"; fi if [ -n "$6" ]; then echo "$6"; fi if [ -n "$7" ]; then echo "$7"; fi if [ -n "$8" ]; then echo "$8"; fi if [ -n "$9" ]; then echo "$9"; fi if [ -n "${10}" ]; then echo "${10}"; fi echo "List of arguments: "$*"" echo "Name of this script: "$0"" if [ $# -lt "$MIN" ]; then echo "Not enough arguments, need $MIN to run."; fi
Para ejemplo, la salida del terminal de $./new.sh q w e r t y u i o p será:
q w e r t y u i o p List of arguments: q w e r t y u i o p Name of this script: ./new.sh
Y la salida de $./new.sh q w e r t y u i o será:
q w e r t y u i o List of arguments: q w e r t y u i o Name of this script: ./new.sh Not enough arguments, need 10 to run.
Pregunta : ¿Qué significa -n?
Comentarios
Responder
[ es otro nombre para el test incorporado, consulte aquí y aquí , también esto .
Esa secuencia de if Las declaraciones probablemente estarían mejor como un bucle. En Bash podríamos usar expansión indirecta:
for ((i=1 ; i <= 10 ; i++)) ; do if [ -n "${!i}" ] ; then echo "${!i}" fi done
El modismo más común probablemente sería usar shift en cada iteración, pero destruye la lista de argumentos.
Además, citando: aquí $0 está fuera de las comillas. En la mayoría de los casos, es más útil mantener todas las expansiones de variables entre comillas, a menos que desee explícitamente división de palabras y expansión de nombre de archivo.
echo "Name of this script: "$0""
Entonces, mejor escriba:
echo "Name of this script: $0"
Comentarios
- Puede usar
shiftdentro de una función y no afectar la lista de argumentos de la persona que llama ', aunque usar una función solo para eso es obviamente un poco hackish.
help test?[y-nsean horribles de buscar.bash -n myscript, realiza una verificación de sintaxis en el script en lugar de ejecutarlo.