Difference between revisions of "SPR720 BASH Scripting Lab"
Chris Tyler (talk | contribs) (New page: = Running a Bash Script = Enter this script into the file "script1" in the current directory (it's a good idea to create a directory for this lab): #!/bin/bash SECRET=$(( RANDOM % 100 ...) |
(No difference)
|
Revision as of 08:50, 16 September 2008
Running a Bash Script
Enter this script into the file "script1" in the current directory (it's a good idea to create a directory for this lab):
#!/bin/bash SECRET=$(( RANDOM % 100 + 1)) INPUT=0 GUESSES=0 echo "Guess the secret: a number between 1 and 100." while [ "$INPUT" -ne "$SECRET" ] do echo -n "Your guess: " read INPUT if [ "$INPUT" -eq "$SECRET" ] then echo "Correct!" elif [ "$INPUT" -gt "$SECRET" ] then echo "Too high." else echo "Too low." fi ((GUESSES++)) done echo "You took $GUESSES tries."
Make the script executable:
chmod u+x script1
Try running the script:
script1
If that doesn't work, specify the directory:
./script1
Or add the current directory to the path:
PATH="$PATH:."
Read through the script and make sure you understand what it does. Use BASH wiki page and the bash manpage for reference.
Reading Bash Scripts
Guess what each of these scripts does, and then test your assumption.
#!/bin/bash if false then echo "1" elif true then echo "2" else echo "3" fi
#!/bin/bash for ((x=0; x<5; x++)) do echo $x done
#!/bin/bash for NAME in /etc/* do if [ -r "$NAME" -a -f "$NAME" ] then wc -c "$NAME" fi done
Writing BASH Scripts
Write scripts to do three of the following tasks:
- Loop through the files in your home directory, and for each readable file, ask whether the file should be printed, mailed to you, or ignored (P/M/I) and then take the appropriate action.
- Display the longest and shortest usernames on the system (usernames are in the first field in /etc/passwd).
- Count the number of users with user IDs between 500 and 10000 on the system (user IDs are the third field in /etc/passwd).
- Display the names of any filesystems which have less than 10% free space available (see the
df
command for this information). - Ask the user for an e-mail address, then send the output of the
dmesg
command to that address. - Count the number of files in the user's home directory which are not readable.
- For each directory in the $PATH, display the number of executable files in that directory.