Bash Script User Input

A entrada do utilizador é uma tarefa comum para qualquer linguagem de programação. É possível obter a entrada de um utilizador em bash script de múltiplas formas. Um comando de leitura é utilizado no script de bash para obter dados do utilizador. Dados únicos ou múltiplos podem ser obtidos em bash script através da aplicação de diferentes opções do comando de leitura. Alguns usos comuns do comando de leitura são mostrados neste tutorial.

Exemplo-1: Usando o comando de leitura simples

Neste exemplo, um único dado é retirado do utilizador e nós imprimimos o valor. Depois de executar o script, o programa aguardará a entrada do utilizador. Quando o utilizador digita os dados e pressiona a introdução, então os dados serão armazenados na variável de resposta. O valor da variável de resposta é impresso mais tarde. Uma coisa, deve lembrar-se que não precisa de usar o símbolo ‘

Output:

Exemplo-2: Usando comando de leitura com opções

-p é usada com comando de leitura para mostrar alguma mensagem útil para o utilizador relacionada com a entrada. A opção -s é utilizada para ocultar o texto do terminal que será digitado pelo utilizador. Isto é chamado modo silencioso e usado para dados de senha. O exemplo seguinte mostra o uso de ambas as opções.

Output:

Exemplo-3: Usando o comando de leitura para obter múltiplas entradas

Se quiser obter múltiplas entradas de cada vez, então tem de usar o comando de leitura com nomes de múltiplas variáveis. No exemplo seguinte, quatro inputs são tomados em quatro variáveis usando o comando de leitura.

#!/bin/bash
# Tomando múltiplas entradas
echo “Digite quatro nomes das suas linguagens de programação favoritas”
leitura lan1 lan2 lan3 lan4
echo “$lan1 é a sua primeira escolha”
echo “$lan2 é a sua segunda escolha”
echo “$lan3 é a sua terceira escolha”
echo “$lan4 é a sua quarta escolha”

p>Output:

p>

Exemplo-4: Usando comando de leitura com o limite de tempo

Se quiser definir a entrada restrita de tempo para o utilizador então tem de usar a opção -t com um comando de leitura. Aqui, o tempo é contado como segundo. No exemplo seguinte, o programa esperará 5 segundos pela entrada do utilizador e se o utilizador não conseguir escrever os dados dentro de 5 segundos, então o programa sairá sem valor.

#!/bin/bash
read -t 5 -p “Digite a sua cor favorita : ” cor
echo $color

Output:

Assim, pode recuperar a entrada do utilizador de diferentes maneiras usando o comando de leitura com base na exigência do seu script.

Para mais informações, veja o vídeo!

no momento de atribuir o valor de uma variável, mas tem de usar o símbolo ‘

Output:

Example-2: Using read command with options

-p option is used with read command to display some helpful message for the user related to input. -s option is used to hide the text from the terminal which will be typed by the user. This is called silent mode and used for password data. The following example shows the use of both options.

Output:

Example-3: Using read command to take multiple inputs

If you want to take multiple inputs at a time then you have to use read command with multiple variable names. In the following example, four inputs are taken in four variables by using read command.

#!/bin/bash
# Taking multiple inputs
echo “Type four names of your favorite programming languages”
read lan1 lan2 lan3 lan4
echo “$lan1 is your first choice”
echo “$lan2 is your second choice”
echo “$lan3 is your third choice”
echo “$lan4 is your fourth choice”

Output:

Example-4: Using read command with the time limit

If you want to set time restricted input for the user then you have to use -t option with a read command. Here, time is counted as second. In the following example, the program will wait for 5 seconds for user’s input and if the user is unable to type the data within 5 seconds then the program will exit without value.

#!/bin/bash
read -t 5 -p “Type your favorite color : ” color
echo $color

Output:

So, you can retrieve input from the user in different ways using read command based on the requirement of your script.

For more information watch the video!

no momento de ler a variável.

#!/bin/bash
echo -n “Qual é a sua comida preferida: “
read answer
echo “Oh! você gosta de $answer!

Output:

Example-2: Using read command with options

-p option is used with read command to display some helpful message for the user related to input. -s option is used to hide the text from the terminal which will be typed by the user. This is called silent mode and used for password data. The following example shows the use of both options.

Output:

Example-3: Using read command to take multiple inputs

If you want to take multiple inputs at a time then you have to use read command with multiple variable names. In the following example, four inputs are taken in four variables by using read command.

#!/bin/bash
# Taking multiple inputs
echo “Type four names of your favorite programming languages”
read lan1 lan2 lan3 lan4
echo “$lan1 is your first choice”
echo “$lan2 is your second choice”
echo “$lan3 is your third choice”
echo “$lan4 is your fourth choice”

Output:

Example-4: Using read command with the time limit

If you want to set time restricted input for the user then you have to use -t option with a read command. Here, time is counted as second. In the following example, the program will wait for 5 seconds for user’s input and if the user is unable to type the data within 5 seconds then the program will exit without value.

#!/bin/bash
read -t 5 -p “Type your favorite color : ” color
echo $color

Output:

So, you can retrieve input from the user in different ways using read command based on the requirement of your script.

For more information watch the video!

Deixe uma resposta

O seu endereço de email não será publicado. Campos obrigatórios marcados com *