Читать книгу Kali Linux Penetration Testing Bible - Gus Khawaja - Страница 70
Script Parameters
ОглавлениеSometimes, you will need to supply parameters to your Bash script. You will have to separate each parameter with a space, and then you can manipulate those params inside the Bash script. Let's create a simple calculator ( simpleadd.sh
) that adds two numbers:
#!/bin/bash #Simple calculator that adds 2 numbers #Store the first parameter in num1 variable NUM1=$1 #Store the second parameter in num2 variable NUM2=$2 #Store the addition results in the total variable TOTAL=$(($NUM1 + $NUM2)) echo '########################' printf "%s %d\n" "The total is =" $TOTAL echo '########################'
You can see in the previous script that we accessed the first parameter using the $1
syntax and the second parameter using $2
(you can add as many parameters as you want).
Let's add two numbers together using our new script file (take note that I'm storing my scripts in the opt
folder from now on):
root@kali:/opt# simpleadd.sh 5 2 ######################## The total is = 7 ########################
There is a limitation to the previous script; it can add only two numbers. What if you want to have the flexibility to add two to five numbers? In this case, we can use the default parameter functionality. In other words, by default, all the parameter values are set to zero, and we add them up once a real value is supplied from the script:
#!/bin/bash #Simple calculator that adds until 5 numbers #Store the first parameter in num1 variable NUM1=${1:-0} #Store the second parameter in num2 variable NUM2=${2:-0} #Store the third parameter in num3 variable NUM3=${3:-0} #Store the fourth parameter in num4 variable NUM4=${4:-0} #Store the fifth parameter in num5 variable NUM5=${5:-0} #Store the addition results in the total variable TOTAL=$(($NUM1 + $NUM2 + $NUM3 + $NUM4 + $NUM5)) echo '########################' printf "%s %d\n" "The total is =" $TOTAL echo '########################'
To understand how it works, let's look at the NUM1
variable as an example (the same concept applies to the five variables). We will tell it to read the first parameter {1
from the terminal window, and if it's not supplied by the user, then set it to zero, as in :‐0}
.
Using the default variables, we're not limited to adding five numbers; from now on, we can add as many numbers as we want, but the maximum is five (in the following example, we will add three digits):
root@kali:~# simpleadd.sh 2 4 4 ######################## The total is = 10 ########################