05 Bash script intro lecture.pdf

Full Transcript

Bash script: introduction Recap week 4 Commands what does su do? what does sudo do? what does whoami do? what is stored in following files: /etc/passwd /etc/shadow which command is used to delete a group? which command is used to create a user? which option is used to cre...

Bash script: introduction Recap week 4 Commands what does su do? what does sudo do? what does whoami do? what is stored in following files: /etc/passwd /etc/shadow which command is used to delete a group? which command is used to create a user? which option is used to create the user's home directory? Permissions what does -rwx------ mean? what does -rw-rw-r-- mean? what do the following do? chmod o+r chmod a=r chmod ug+x chmod 777 chmod 754 To be covered (Ess 11) most of module 11 - basic scripting (but not loops!) basic scripting if statement case statement demos variables evaluate exit codes hello.sh environment variables compare numbers greetings.sh compare strings whoareyou.sh PATH variable findfiles.sh check file existence, file quotes permissions checkuser.sh exit codes complex conditions checkargs.sh checkusername.sh arguments deletefile.sh checkstaff.sh Basic scripting (Ess 11) Basic scripting a script is simply a list of executable commands stored in a file we will be writing Bash script files stored with a.sh extension sh indicates a shell script file needs to be executable to run execute permission NB: all the following examples could be run at the command prompt, though we will put them in a file Benefits of scripts automate tasks reduce risk of errors combine sequences of commands into a single command share procedures between users provide controlled access for users rapid prototyping Available shell options /etc/shells specifies which shells are available on a distro cat /etc/shells where else have we seen /bin/bash? Recap nano text editor arrow keys to move around delete and backspace to delete text context-sensitive options at bottom of screen CTRL&X to quit prompted to save file Variables Variables (Ess 11.4.1) variables store values within a script or terminal session to declare a variable with the value "Jan" name="Jan" to reference a variable $name to reference a variable inside a string echo "My name is $name" Environment variables system automatically creates environment variables when new shell opened uppercase names by convention available system-wide HOME PATH environment variables are handled in same way as any other variable An aside about PATH variable (1 of 2) PATH variable contains a list of directories the shell searches for commands directories are separated by : paths searched in order they are listed if command not found in any directory, shell will output "command not found" normally due to invalid command but can be directory containing command not in PATH variable An aside about PATH variable (2 of 2) can add directories containing any custom software to the PATH variable must append or prepend values to PATH variable, not overwrite it otherwise will lose access to existing commands Quotes Quotes (Ess 5.6) quotes cause the enclosed text to be treated differently to output: My name, Jan, is stored in $name It is currently Fri Nov 4 13:30:12 UTC 2022 assign name="Jan" (if not already done) Double quotes (Ess 5.6) double quotes allow variable and command substitution ie. they are evaluated before being output echo "My name, $name, is stored in $name" echo "My name, $name, is stored in \$name" echo "It is currently $(date)" commands must be enclosed in parentheses Single quotes (Ess 5.6) single quotes prevent variable and command substitution echo 'My name, $name, is stored in $name' echo 'It is currently $(date)' Let's code! Development steps TO DO: create directory called week5 change to week5 directory create file how? create new file with sh as file extension how? make file sh indicates that it executable is a shell script make file executable how? run file run file using either./ or sh followed by name of file DEMO: first script (1 of 3) (Ess 11.2) script to output "Hello World!" to the screen create a file called hello.sh add code to script #!/bin/bash echo 'Hello World!' save file DEMO: first script (2 of 3) (Ess 11.2) (try to ) run the executable file (script) from the current directory./hello.sh why is there an error? check permissions with ls -l DEMO: first script (3 of 3) (Ess 11.2) change permissions chmod u+x hello.sh what does this do? how else could we do this? run script./hello.sh or sh hello.sh./ runs named script in current directory Using variables DEMO: saving results in variables store username and time in variables, then output them in a greeting create a file called greetings.sh #!/bin/bash see link for options username=$(whoami) for date formatting currenttime=$(date +%H:%M) echo "Hello ${username}, it is ${currenttime}" change permissions and run file DEMO: getting input from user prompt user to enter name, then output a personalised greeting create a file called whoareyou.sh #!/bin/bash echo -n "What is your name? " -n in an echo statement read name prevents newline at end echo "Hello $name!" change permissions and run file DEMO: using variables in commands find all files of specified type in /Documents create a file called findfiles.sh #!/bin/bash echo -n "What file extension do you want to look for? " read extension find ~/Documents -name "*.$extension" change permissions and run file Conditionals Exit codes commands return an exit code to indicate success of operation 0 represents no error any other value (1 - 255) represents an error defined by that particular command exit code stored in the $? environment variable success failure error code if statement (Ess 11.4.2) perform action based on condition can put newline instead of semicolon possible conditions: evaluate return value of a command (0 for success) compare numbers compare strings if condition1; then check file existence, file permissions # do this if condition1 is true elif condition2; then # do this if condition2 else # otherwise do this fi Passing arguments we have used many commands that accept arguments which commands? argument values are automatically available within the script $0 name of the script $1 value of the first parameter $2 value of the second parameter... $# number of parameters passed $@ all parameters passed DEMO: evaluate exit code of command check whether the value passed as a parameter exists in /etc/passwd create a file called checkuser.sh #!/bin/bash -q option will prevent output echo -n $1 being displayed (quiet mode) if grep -q $1 /etc/passwd; then do not forget to echo " is a current user" pass a parameter else echo " is not a current user" fi change permissions run file with parameter Numeric comparisons numeric comparisons are enclosed within [ ] numbers are compared using symbolic expressions -eq must include a space after [ and before ] -ge -gt -le if [ $age -eq 21 ] -lt if test $age -eq 21 -ne DEMO: compare numbers check number of arguments provided is greater than 0 create a file called checkargs.sh #!/bin/bash must include a space after [ and before ] if [ $# -eq 0 ]; then echo "You must provide at least 1 argument" fi change permissions run file (with and without parameters) String comparisons string comparisons are enclosed within [ ] comparisons are case-sensitive strings are compared using equality symbols returns false = != if [ 01 = 1 ] if [ 01 -eq 1 ] DEMO: compare strings check if user enters correct username create a file called checkusername.sh #!/bin/bash echo -n "What is your username? " read name if [ $USER = $name ]; then echo "Correct username" else echo "Incorrect username" fi Complex conditions can combine the result of separate tests using Boolean operators && all parts must be true || at least one part must be true ! negate the boolean value if [ 01 = 1 ] && [ 01 -eq 1 ] if [ 01 = 1 ]; then if [ 01 -eq 1 ]; then #executed if both true File existence and permissions several options are provided to check file existence and permissions: -e file true if "file" exists -f file true if "file" is a regular file -d file true if "file" is a directory -s file true if "file" has non-zero size (ie has content) -r file true if "file" is readable -w file true if "file" is writable [ -f Documents/words ] echo $? -x file true if "file" is executable Returning exit codes in addition to checking exit code from other commands, can also return exit code from scripts exit 1 DEMO: check file existence (1 of 3) prompt the user for a filename and delete the file if it is empty, outputting suitable messages if the file does not exist or is not empty and returning exit codes create an empty file called empty.txt how? create a file called notempty.txt containing "File is not empty" how? create new file called deletefile.sh to contain script #!/bin/bash echo -n "Which file do you want to delete? " DEMO: check read file file existence if [ ! -f $file ]; then (2 of 3) echo "$file does not exist" exit 1 elif [ -s $file ]; then echo "cannot delete $file as it is not empty" exit 2 else rm $file echo "$file has been deleted" exit 0 fi DEMO: check file existence (3 of 3) Case statement case... esac is alternative to multiple elif clauses within if... else... fi statement multiple cases statements associated with the first matching case are executed ) delimits end of values for a case | used to separate alternative values for a case * default case which is executed if no other cases match equivalent to else ;; ends the statements to be executed if the case is true ;& allows fall-through so that following cases may also match #!/bin/bash echo -n "Staff name? " read name DEMO: check case $name in strings using Fiona) case echo "Module leader" ;& (1 of 2) Jan) echo "Delivers lectures and tutorials" ;; Andy|Russell) echo "Tutorials" ;; *) echo "Not a lecturer on WDOS" esac DEMO: check strings using case (2 of 2) basic scripting programs variables hello.sh environment variables greetings.sh What we PATH variable quotes whoareyou.sh findfiles.sh have covered exit codes checkuser.sh arguments checkargs.sh checkusername.sh deletefile.sh if statements checkstaff.sh evaluate return value of command compare numbers compare strings check file existence, file permissions complex conditions case statement Any questions?

Use Quizgecko on...
Browser
Browser