martedì 20 marzo 2012

Unix IF

Non mi capita molto spesso di scrivere script di shell, ma ogni volta mi capita di litigare con l'if di cui non ricordo mai la sintassi.
Questa volta ho trovato aiuto in questa pagina http://www.dreamsyssoft.com/sp_ifelse.jsp e ne riporto in parte il contenuto per comodità:


If/Else

In order for a script to be very useful, you will need to be able to test the conditions of variables. Most programming and scripting languages have some sort of if/else expression and so does the bourne shell. Unlike most other languages, spaces are very important when using an ifstatement. Let's do a simple script that will ask a user for a password before allowing him to continue. This is obviously not how you would implement such security in a real system, but it will make a good example of using if and else statements. 
#!/bin/sh
# This is some secure program that uses security.

VALID_PASSWORD="secret" #this is our password.

echo "Please enter the password:"
read PASSWORD

if [ "$PASSWORD" == "$VALID_PASSWORD" ]; then
 echo "You have access!"
else
 echo "ACCESS DENIED!"
fi
Remember that the spacing is very important in the if statement. Notice that the termination of the if statement is fi. You will need to use thefi statement to terminate an if whether or not use use an else as well. You can also replace the "==" with "!=" to test if the variables are NOT equal. There are other tokens that you can put in place of the "==" for other types of tests. The following table shows the different expressions allowed. 
Comparisons:
-eqequal to
-nenot equal to
-ltless than
-leless than or equal to
-gtgreater than
-gegreater than or equal to

File Operations:
-sfile exists and is not empty
-ffile exists and is not a directory
-ddirectory exists
-xfile is executable
-wfile is writable
-rfile is readable

Nessun commento:

Posta un commento