congdong007

Penetration Test、Software Developer

0%

Bash Scripting 04 - Reading User Input

Command-line arguments are a form of user input, but we can also capture interactive user input
while a script is running with the read command. In this example, we will use read to capture user
input and assign it to a variable:

1
2
3
4
5
6
7
8
9
10
kali@kali:~$ cat ./input.sh
#!/bin/bash
echo "Hello there, would you like to learn how to hack: Y/N?"
read answer
echo "Your answer was $answer"
kali@kali:~$ chmod +x ./input.sh
kali@kali:~$ ./input.sh
Hello there, would you like to learn how to hack: Y/N?
Y
Your answer was Y

We can alter the behavior of the read command with various command line options. Two of the
most commonly used options include -p, which allows us to specify a prompt, and -s, which makes
the user input silent. The latter is ideal for capturing user credentials:

1
2
3
4
5
6
7
8
9
10
11
kali@kali:~$ cat ./input2.sh
#!/bin/bash
# Prompt the user for credentials
read -p 'Username: ' username
read -sp 'Password: ' password
echo "Thanks, your creds are as follows: " $username " and " $password
kali@kali:~$ chmod +x ./input2.sh
kali@kali:~$ ./input2.sh
Username: kali
Password:
Thanks, your creds are as follows: kali and nothing2see!