1.Demo
#!/bin/bash
echo hello world
$ chmod a+rx script.sh
$ ./script.sh
2.Variables-Part I
· No space around the “=” sign
· read (Automatically places quotes around its input)
· Scope of Variables
· export
· source a script via the “.”(dot) command
· enclose the variable itself in curly brackets
3.Variable-Part II
· $0 is the basename of the program as it was called.
· $1 … $9 are the first 9 additional parameters the script was called with.
· $@ is all parameters $1 … whatever.
· $*, is similar, but does not preserve any whitespace, and quoting
· $# is the number of parameters the script was called with.
· $? is the exit value of the last run command
· $$ is the PID (Process IDentifier) of the currently running shell.
· $! is the PID of the last run background process. This is useful to keep track of the process as it gets on with its job.
· IFS is the Internal Field Separator. The default value is SPACE TAB NEWLINE
4.WildCards
5.Escape Characters
Most characters(*,’,etc) are not interpreted by means of placing them in double quotes.",$,` and \ are interpreted by the shell
6.Loops
① For Loops
#!/bin/bash
for i in hello 1 * 2 goodbye
do
echo "Looping ... i is set to $i"
done
② While Loops
#!/bin/bash
INPUT_STRING=hello
while [ "$INPUT_STRING" != "bye" ]
do
echo "bye to quit"
read INPUT_STRING
done
The colon(:)always evaluates to true.
7.Case
The case statement saves going through a whole set of if … then … else statements
#!/bin/sh
echo "Please talk to me ..."
while :
do
read INPUT_STRING
case $INPUT_STRING in
hello)
echo "Hello yourself!"
;;
bye)
echo "See you again!"
break
;;
*)
echo "Sorry, I don't understand"
;;
esac
done
echo
echo "That's all folks!"
8.Test
#!/bin/sh
if [ "$X" -lt "0" ]
then
echo "X is less than zero"
fi
if [ "$X" -gt "0" ]; then
echo "X is more than zero"
fi
[ "$X" -le "0" ] && \
echo "X is less than or equal to zero"
[ "$X" -ge "0" ] && \
echo "X is more than or equal to zero"
[ "$X" = "0" ] && \
echo "X is the string or number \"0\""
[ "$X" = "hello" ] && \
echo "X matches the string \"hello\""
[ "$X" != "hello" ] && \
echo "X is not the string \"hello\""
[ -n "$X" ] && \
echo "X is of nonzero length"
[ -f "$X" ] && \
echo "X is the path of a real file" || \
echo "No such file: $X"
[ -x "$X" ] && \
echo "X is the path of an executable file"
[ "$X" -nt "/etc/passwd" ] && \
echo "X is a file which is newer than /etc/passwd"