User input (Bash): verschil tussen versies

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen
(Nieuwe pagina aangemaakt met ' == Sources == * https://ryanstutorials.net/bash-scripting-tutorial/bash-input.php')
 
 
Regel 1: Regel 1:
 +
== Direct mode ==
  
 +
Interestingly, <code>man read</code> doesn't exist, but you can use <code>read</code> in direct mode:
 +
 +
<pre>
 +
$ read blub; echo $blub
 +
 +
hallo ← User input
 +
hallo ← Echod back to console
 +
</pre>
 +
 +
== Simple script ==
 +
 +
<code>read</code> is probably more relevant in a script than in direct mode:
 +
 +
<pre>
 +
#!/bin/bash
 +
 +
read response
 +
echo "Response: $response
 +
</pre>
 +
 +
When executing this script, there is just a blinking prompt. Input is subsequently echod.
 +
 +
== Including prompt ==
 +
 +
<pre>
 +
#!/bin/bash
 +
 +
read -p "Please type something" response
 +
echo "Response: $response
 +
</pre>
 +
 +
The flag <code>-p</code> indentifies the next argument as prompt. Without this flag, an error would occur.
 +
 +
== Including silent prompt ==
 +
 +
Nice of asking for e.g., a password:
 +
 +
<pre>
 +
#!/bin/bash
 +
 +
read -ps "Password?" response
 +
</pre>
 +
 +
== read usage ==
 +
 +
No man page seems to exit, but sometimes (like through <code>read -help</code>) some help can be get:
 +
 +
<pre>
 +
read: usage: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
 +
</pre>
 
== Sources ==
 
== Sources ==
  
 
* https://ryanstutorials.net/bash-scripting-tutorial/bash-input.php
 
* https://ryanstutorials.net/bash-scripting-tutorial/bash-input.php

Huidige versie van 21 jul 2022 om 12:48

Direct mode

Interestingly, man read doesn't exist, but you can use read in direct mode:

$ read blub; echo $blub

hallo ← User input
hallo ← Echod back to console

Simple script

read is probably more relevant in a script than in direct mode:

#!/bin/bash

read response
echo "Response: $response

When executing this script, there is just a blinking prompt. Input is subsequently echod.

Including prompt

#!/bin/bash

read -p "Please type something" response
echo "Response: $response

The flag -p indentifies the next argument as prompt. Without this flag, an error would occur.

Including silent prompt

Nice of asking for e.g., a password:

#!/bin/bash

read -ps "Password?" response

read usage

No man page seems to exit, but sometimes (like through read -help) some help can be get:

read: usage: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]

Sources