shell is a script language and belongs to interpreted language
Variables
One big difference between Shellscript and other programming languages is that there must be no spaces between “=” sign. Such a design has its reason, as shell is not only a programming language, but also a command line interpreter. If you use VAR = value, it’s like being interpreted as running some command called “VAR” and two arguments named “=” and “value”. Therefore that is impossible to run successfully.
Shellscript uses $VAR to reference a variable that has been defined before.
Scope of variables
“local” variable
When running a script file, Linux creates a new process with a unique ‘pid’ for it. We can only use variables created in the script file in this 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 . command for sourcing a script file. This is how the configuration files like .bashrc or .vimrc works (source .bashrc every time before opening a bash and source .vimrc whenever before opening a vim program).
the priority
Think such an occasionally case, if a local defined variable has the same name as a global variable, the local one will have priority. If the local one doesn’t exist or hasn’t been defined yet, the interpreter will use the global ones. If none of them exist, a ‘null’ will be given out.
Statements
if语句
1 | if [ 布尔表达式 ] |
case 语句
1 | case 变量 in |
循环语句
循环语句有多种写法
1 | for i in {1..10} |
Special characters
$$$$ indicates the process id(PID) that running the script.
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 separated words, the curly braces will prevent touch creating two new files for it.
Comment
Shell uses # to comment a whole line.
Running the script
Write scripts into a readable and executable file. The first line can indicate which 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
buit-in commands
echo: takes one or more parameters separated 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 calculator 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: can be used to detect certain files or related properties, and the judgment symbol [] is equivalent.
`test -n string: returns true is the string’s length is over 0
For more Linux builtin commands, go to this article.
Comments
shortnamefor Disqus. Please set it in_config.yml.