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.gchmod 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 scriptMYVAR="something"NOTE: no $ when set
MYPATH=./mydir
2.2 get in the scriptecho "${MYVAR} is my var"so, always use $ to get it
ls -al "${MYPATH}"
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: linux, shell scripts
About this blog
I had a website about 10 year ago? Couldn’t really remember now, but it was surely a long, long time ago, and I stopped updating it cos I was occupied by all the work and hobbies - ironically, these were all web-related.
Finally, I decided to revive my webiste, and this time, in the form of a blog - hope this time I can keep it updated. Well, I’ve downloaded the iphone wordpress app, hoping it will help.
Leave a reply
You must be logged in to post a comment.