Variables
One big difference between Shellscript and other programming languages is that there must be no spaces between “=” sign. It has its reason. Because when in a shell, if you use VAR = value
, it’s just like running some command called “VAR” and two arguments named “=” and “value”. Therefore that is impossible to run successfully.
Shellscript uses $VAR
to indicate it’s a variable that has been defined before.
Scope of variables
“local” variable
When we run a scipt, Linux creates a new process with a unique ‘pid’ for it. So we can only use variables created in this files in the process. Once the process is ending or we are in another process, we cannot use the variables.
“global” variable
However, like the concept of ‘environmental variables’ in Windows, Linux also has global-scope variables by using the source
commands or . ./*.sh
for sourcing a scipt file. This is how the configuration files like .bashrc
or .vimrc
work (source .bashrc
everytime before opening a bash and source .vimrc
everytime before openning a vim program).
the priority
Think a occasionally case, if a local defined variable has the same name as a global variable, the local one has priority. If the local one doesn’t exist or hasn’t been defined yet, use the global ones. If none of them exist, give out a null.
Statements
if语句
1 | if [ 布尔表达式 ] |
case 语句
1 | case 变量 in |
循环语句
循环语句有多种写法
1 | for i in {1..10} |
特殊符号
$$ 表示运行脚本的进程号(PID)
The use of curly braces “{}” can enclose a variable into it even if characters follow with no spaces. See the example below.
1 | #!/bin/sh |
There is one more advantage that if we type two seperated words, the curly braces will prevent touch
creating two new files for it.
Comment
Shellscript uses #
to comment a whole line.
Running the script
Write scripts into a readable and executable file. The first line can indicate the program(/bin/sh) to run it. If you are using GNU/Linux, /bin/sh is normally a symbolic link to bash.
1 | #!/bin/sh |
Functions
buitin commands
echo
: takes one or more parameters seperated by blank characters(spaces or tabs).
expr
: Print the value of EXPRESSION to standard output. It supports logical expressions. It can be also used as a simple caculator for integers in shell. But caution that the asteroid *
is regarded as a wildcard. So when you do multiplication, you should use \*
.
read
: reads a line from standard input into the variable supplied.
touch
: create a empty file by the name
test
: 可以用来检测某些文件或者是相关的属性,和判断符号 [] 等价test -n 字符串
: 字符串长度不为零则为真
For more Linux builtin commands, go to this article.
Comments
shortname
for Disqus. Please set it in_config.yml
.