-
Creating Shell Scripts
- Using Linux command in a script
- Using arguments
- Using variables
- Using conditional expressions if / else
- Using loops
- Using functions
- Setting the script’s exit value
-
Beginning a Shell Script
- Plain text files Use any text editor
- First line identifies the shell used to run it
- set the “execute bit” on
- chmod 755 testscript
- Example:#!/bin/bash
- First two character are special code
- Tells the kernel that this is a script and where to find the program to interpret the script
- The line is sometimes called: shebang, hashband, hashpling, or poundbang
-
multiple ways to run script
- ./testscript (most appropriate)
- bash testscript
- sh testscript
- Can place the script in a directory within the “PATH”
- By doing the above you will not have to specify any path to find the script
- For example place the script in: /usr/local/bin
-
If get error message for command:
...No such file or directory
- $ which command
- /location/command
-
environmental variables
- $PATH
- $HOME home directory of logged in user
- $PROMPT
- $PS1
- $HOSTNAME name of current machine
- $HISTSIZE number of entries in History file
- $USER
- $LOGNAME login name
- $PWD current working directory
- $SHELL name of current shell
- $? special variable-exit status(return value) of most recently executed command
-
Running a script named “testscript” and passing two variables
What are variable names
- ./testscript alpha beta
- $0 $1 $2
-
script that returns the name passed
- same as Hello_You.sh
- chmod 755 Hello_You.sh
- ./Hello_You.sh someName
- bash Hello_You.sh someName
- sh Hello_You.sh someName
-
assignment
no spaces before and after =
-
if
- if [ conditional-expression ]
- then
- commands
- else
- other-commands
- fi
-
compound if
- if [ command ] && [ command ]
- then
- additional-commands
- fi
- if [ command ] || [ command ]
- then
- additional-commands
- fi
-
case syntax
- case word in
- pattern1) command(s) ;;
- pattern2) command(s) ;;
- ...
- esac
*) //I guess is any other case
-
for loop syntax
- for variable in list
- do
- commands
- done
-
while loop syntax
- while [ condition ]
- do
- commands
- done
- #!/bin/bash
- echo "What is your name? "
- read Me
- while [ $Me = 'fred' ]
- do
- echo "Go away fred"
- echo "What is your name? "
- read Me
- done
- echo "Hello $Me"
-
function syntax
- function function_name() {
- commands
- } //keyword function is optional
- !#/bin/bash
- doit() {
- cp $1 $2}
- function check() {
- if [ -s $2 ]
- then
- echo "Target file exists! Exiting!"
- exit
- fi
- }
- check $1 $2
- doit $1 $2
-
Exit script
- $ echo $?
- 0
- -----------------
- !#/bin/bash
- [...]
- exit 42
- $ echo $?
- 42
-
list all files in the current working directory with a file extension of “.txt”
- #!/bin/bash
- echo testscript starting
- logger testscript starting
- for d in `ls *.txt` ; do # notice the backticks
- echo $d
- done
- echo testscript ending
- logger testscript ending
|
|