Necesito leer un valor de la terminal en un script bash. Me gustaría poder proporcionar un valor predeterminado que el usuario pueda cambiar.
# Please enter your name: Ricardo^
En este script, el mensaje es “Por favor, introduzca su nombre:” el valor predeterminado es “Ricardo” y el cursor estará después del valor predeterminado. ¿Hay alguna manera de hacer esto en un script bash?
puede usar la expansión de parámetros, por ejemplo
read -p "Enter: " name name=${name:-Richard} echo $name
read -e -p "Enter Your Name:" -i "Ricardo" NAME echo $NAME
En Bash 4:
name="Ricardo" read -e -i "$name" -p "Please enter your name: " input name="${input:-$name}"
Esto muestra el nombre después del mensaje como este:
Please enter your name: Ricardo
con el cursor al final del nombre y le permite al usuario editarlo. La última línea es opcional y obliga al nombre a ser el valor predeterminado original si el usuario borra la entrada o el valor predeterminado (presentando un valor nulo).
Código:
IN_PATH_DEFAULT="/tmp/input.txt" read -p "Please enter IN_PATH [$IN_PATH_DEFAULT]: " IN_PATH IN_PATH="${IN_PATH:-$IN_PATH_DEFAULT}" OUT_PATH_DEFAULT="/tmp/output.txt" read -p "Please enter OUT_PATH [$OUT_PATH_DEFAULT]: " OUT_PATH OUT_PATH="${OUT_PATH:-$OUT_PATH_DEFAULT}" echo "Input: $IN_PATH Output: $OUT_PATH"
Muestra de ejecución:
Please enter IN_PATH [/tmp/input.txt]: Please enter OUT_PATH [/tmp/output.txt]: ~/out.txt Input: /tmp/input.txt Output: ~/out.txt
Encontré esta pregunta, buscando una manera de presentar algo como:
Something interesting happened. Proceed [Y/n/q]:
Usando los ejemplos anteriores deduje esto:
echo -n "Something interesting happened. " DEFAULT="y" read -e -p "Proceed [Y/n/q]:" PROCEED # adopt the default, if 'enter' given PROCEED="${PROCEED:-${DEFAULT}}" # change to lower case to simplify following if PROCEED="${PROCEED,,}" # condition for specific letter if [ "${PROCEED}" == "q" ] ; then echo "Quitting" exit # condition for non specific letter (ie anything other than q/y) # if you want to have the active 'y' code in the last section elif [ "${PROCEED}" != "y" ] ; then echo "Not Proceeding" else echo "Proceeding" # do proceeding code in here fi
Espero que alguien ayude a no tener que pensar la lógica, si se encuentran con el mismo problema
Acabo de usar este patrón, que prefiero:
read name || name='(nobody)'
name=Ricardo echo "Please enter your name: $name \c" read newname [ -n "$newname" ] && name=$newname
Establecer el predeterminado; Imprímelo; lee un nuevo valor; si hay un nuevo valor, úselo en lugar del valor predeterminado. Hay (o hubo) algunas variaciones entre shells y sistemas sobre cómo suprimir una nueva línea al final de un prompt. La notación ‘\ c’ parece funcionar en MacOS X 10.6.3 con un bash 3.x, y funciona en la mayoría de las variantes de Unix derivadas del Sistema V, utilizando conchas Bourne o Korn.
También tenga en cuenta que el usuario probablemente no se daría cuenta de lo que está sucediendo detrás de escena; sus nuevos datos se ingresarán después de que el nombre ya esté en la pantalla. Podría ser mejor formatearlo:
echo "Please enter your name ($name): \c"
#Script for calculating various values in MB echo "Please enter some input: " read input_variable echo $input_variable | awk '{ foo = $1 / 1024 / 1024 ; print foo "MB" }'
El parámetro -e y -t no funciona en conjunto. Probé algunas expresiones y el resultado fue el siguiente fragmento de código:
QMESSAGE="SHOULD I DO YES OR NO" YMESSAGE="I DO" NMESSAGE="I DO NOT" FMESSAGE="PLEASE ENTER Y or N" COUNTDOWN=2 DEFAULTVALUE=n #----------------------------------------------------------------# function REQUEST () { read -n1 -t$COUNTDOWN -p "$QMESSAGE ? Y/N " INPUT INPUT=${INPUT:-$DEFAULTVALUE} if [ "$INPUT" = "y" -o "$INPUT" = "Y" ] ;then echo -e "\n$YMESSAGE\n" #COMMANDEXECUTION elif [ "$INPUT" = "n" -o "$INPUT" = "N" ] ;then echo -e "\n$NMESSAGE\n" #COMMANDEXECUTION else echo -e "\n$FMESSAGE\n" REQUEST fi } REQUEST