Quick note of shell script
1. basics
1.1 script engine
specify it like:
#!/bin/sh or #!/bin/bash ...
just pick a system u like.

1.2 permission
the file needs to have a+x permission
e.g
chmod a+x myscript

1.3 want to run it anywhere?
edit your .profile or .bash_profile to have the path to the script included. e.g.
PATH=$PATH:$HOME/bin:my-script-path
log out and log in again, you can just type the script name to run it

2. get variables and set variables
2.1 set in the script
MYVAR="something"
MYPATH=./mydir
NOTE: no $ when set

2.2 get in the script
echo "${MYVAR} is my var"
ls -al "${MYPATH}"
so, always use $ to get it

2.3 if you want to set it again
same way:
MYVAR="now it's changed!"
without the $, notice.

2.4 get from user input
simply,
read [var-name]
e.g.
read inputpath;
echo "You have entered input path: ${inputpath}"

3. tests
simply use [] for tests, NOTE: spacing is very important, make sure there’s only one space between each operator.

The command test exits with zero status if and only if a given condition is true. Conditions are boolean (true/false) expressions involving:

string comparison (=, !=)
numeric comparison (-eq, -ne, -lt, -le, -gt, -ge)
tests on files (given a file name, can test

    whether it is a regular file (-f),
    whether it is a directory (-d),
    whether it is writeable (-w), etc)

For example, test “$x” = “$y” returns success when the variables x and y hold the same string, and test -d “$dir” returns success if the variable dir holds the name of a directory.

NOTE The test command expects each operator and operand to be a separate argument. Therefore one must put spaces around them on the command line.

e.g

#!/bin/bash
echo "Enter your name"
read inputname
if [ ! "$inputname" ]; then
    echo "Name is empty!"
    exit 1
else
    echo "You name is $inputname"
fi

more to follow…

Technorati Tags: ,