It takes some time for BASH Shell to have a complete and in-depth understanding, but sometimes it is necessary to quickly master its basic usage and write simple programs to meet the needs of the project, then you can read the following article, otherwise you do not need to spend time on the following text.
The first thing to clarify is that it is not necessary to make a detailed study of shell script programming. As pointed out in the title of this article, this is a quick guide to introduce bashshell script syntax. If you want to study it in depth, we suggest you buy a book about shell script programming ;-). Well, now let's start learning and start timing the table!
Body:
Common environment variables:
$ Path-sets the search path for executable programs, which is similar to the $ PATH variable in msdos.
$ Home-your local directory (home ).
$ Mail-Save the mail delivery path set by the user.
Saves a string consisting of Characters Used for character separation in the command line. This string usually contains spaces, tabs, and line breaks. To view the information, perform the following operations on the octal dump:
$ Echo $ ifs | OD-BC
PS1 and PS2-primary and secondary prompts). PS1 is set to $ by default, and PS2 is set to '>'. To view PS2, run the following command:
$ ls |
Press enter.
$ User-user login name.
$ Term-terminal type identifier. Sometimes you must set the correct terminal ID for the editor to work properly.
$ Shell-you can view the shell type during login.
Note: To view the values of the preceding variables, simply use the echo command to add the $ variable name. For example:
$ echo $USER
ravi
The value of $ user is obtained.
BASH Shell programming rules
1) the first line of the script must be:
#!/bin/bash
# Well number, followed! Exclamation point, followed by the Shell path. This statement tells the parser that this is a shell script and specifies the shell path.
2) grant the execution permission to the script before executing the script:
$ chmod ugo+x your_shell_script.sh
3) Name the script with the. Sh suffix. This is a shell script. This is not necessary, but it is a standard. That's right.
Condition Statement
If
If statement-determine the condition command and then decide the process execution.
The words in blue are required. Red is optional.
Syntax:
if condition_is_true
then
execute commands
else
execute commands
fi
The IF condition can be multi-path selection (branch structure ). In this way, multiple conditions can be judged.
if condition_is_true
then
execute commands
elif another_condition_is_true
then
execute commands
else
execute commands
fi
Example:
if grep "linuxhelp" thisfile.html
then
echo "Found the word in the file"
else
echo "Sorry no luck!"
fi
If partner-test command
Test is a built-in shell command. Test judges the right operand. Returns true or false. For this reason, test uses a specific operator for condition judgment, as shown below:
Relational operators
-EQ equal to equals
-Lt less than is less
-GT greater
-Ge greater than or equal to must be greater than or equal
-Lt less than is less
-Le less than or equal
File-related tests:
-F file is true if it exists and is a regular file
-R file is true if it is readable.
-W file exists and can be written, true
-X file exists and can be executed, it is true
-D file is a folder, which is true.
-S file exists and is true if it is not zero
String test:
-n str True if string str is not a null string
-z str True if string str is a null string
str1 == str2 True if both strings are equal
str1 != str2 True if both strings are unequal
str True if string str is assigned a value
and is not null.
The above means:
-N str: true if STR is not null
-Z str: true if STR is null
Str1 = str2 true if two strings are equal
Str1! = Str2: true if two strings are not equal
STR is true if STR has a non-null value.
The test function also allows multiple expressions to be verified in a row.
-a Performs the
AND function
-o Performs the
OR function
Example:
test $d -eq 25 ; echo $d
The above indicates that if the value of the $ D variable is 25, this value is output.
test $s -lt 50; do_something
if [ $d -eq 25 ]
then
echo $d
fi
In the above example, I mark it with brackets and it is processed by test. In fact, it can be processed in the following way:
if
[ $str1 == $str2
]
then
do something
fi
if [
-n "$str1" -a -n "$str2" ]
then
echo 'Both $str1 and $str2 are not null'
fi
The above indicates that if neither of the strings is null, the echo command is executed.
Notes for using test:
If you use [] to replace test, add a space before and after [, otherwise it will not be parsed.
Note: The test operand is limited to an integer, And the decimal number is automatically truncated.
Do not use wildcards to check the matching of strings. In Shell, wildcards are used to match the names of directories with common names, rather than the test command.
Case statement
Case is another statement provided by shell as a condition judgment.
Syntax:
case expression in
pattern1) execute commands ;;
pattern2) execute commands ;;
...
esac
The keywords here are in, case and esac. The ';' is used as option Terminators. The construct also uses ')' to delimit the pattern from the action.
The syntax contains three keywords: case, in, and esac.
Symbol; is the end mark of each option.
And the right Parenthesis) is used to split the pattern and action.
Example:
...
echo "Enter your option : "
read i;
case $i in
1) ls -l ;;
2) ps -aux ;;
3) date ;;
4) who ;;
5) exit
esac
Note: The last option is not required; you can add it if you like it.
Another example:
case `date |cut -d" " -f1` in
Mon) commands ;;
Tue) commands ;;
Wed) commands ;;
...
esac
Case can match more than one pattern. You can use wildcards to match the pattern;
...
echo "Do you wish to continue? (y/n)"
read ans
case $ans in
Y|y) ;;
[Yy][Ee][Ss]) ;;
N|n) exit ;;
[Nn][Oo]) exit ;;
*) echo "Invalid command"
esac
In the above example, if you enter yes, or any other combination, it can be matched.
At this point, the introduction of conditional statements has come to an end.
Loop statement
While Loop
Syntax:
while condition_is_true
do
execute commands
done
Example:
while [ $num -gt 100 ]
do
sleep 5
done
while :
do
execute some commands
done
The above code will execute an infinite loop, of course you can use while True to replace while :.
Here I will introduce the loop-related keywords: Break and continue.
Break-this keyword can exit the loop and terminate the execution.
Continue-this keyword can pause the execution of the following statement in the current loop and then execute the next loop.
Until Loop
If the condition after until is false, the DO command will be executed cyclically.
until false
do
execute commands
done
...
until [ -r myfile ]
do
sleep 5
done
The above code is executed repeatedly until the file myfile can be read.
The above code will be executed repeatedly until myfile is readable.
For Loop
Syntax:
for variablein list
do
execute commands
done
Example:
...
for x
in 1 2 3 4 5
do
echo "The value of x is $x";
done
In the preceding example, we list the numbers 1-5.
The following is another example:
for var
in $PATH $MAIL $HOME
do
echo $var
done
If you have a folder, it will contain the *. Java file to be compiled.
You can write such a shell script:
...
for file
in *.java
do
javac $file
done
Note: As shown in the preceding example, wildcards can be used in the script.
Some special symbols and meanings of writing shell scripts:
$* - This denotes all the parameters passed to the script
at the time of its execution. Which includes $1, $2
and so on.
$0 - Name of the shell script being executed.
$# - Number of arguments specified in the command line.
$? - Exit status of the last command.
The above symbols are called positional parameters. Let me use the following example to parse the usage of location parameters.
Assume that I have a script my_script.sh and execute the following:
$ ./my_script.sh linux is a robust OS
As shown above, I passed five parameters to the script. Here, the value of the location parameter is:
$ *-The values include 'linux ', 'ais', 'A', 'robust', and 'OS '.
$0-the value is the name of the script file my_script.sh-executed.
$ #-Value: 5-number of parameters.
$-The value is the ID of the current process. You can run the script to create a temporary file (if any)
Use this parameter to get a unique name.
$1-value of the first parameter, that is, 'linux'
$2-value of the first parameter, that is, 'is'
... And so on.
Set and shift statements
Set-associates a value with the location parameter.
For example:
$ set `date`
$ echo $1
$ echo $*
$ echo $#
$ echo $2
Shift-directly transfer the value of the location parameter to the next parameter (a location parameter with a smaller number ).
Shift is performed once.
Example:
$ set `date`
$ echo $1 $2 $3
$ shift
$ echo $1 $2 $3
$ shift
$ echo $1 $2 $3
View the process ID of the current shell script, which can be used:
$ echo $$
2667
You can use the following script for verification:
$ ps -f |grep bash
Read statement
Read allows your shell scripts to implement human-computer interaction.
The read Statement allows you to set the variable value when executing shell.
When the script runs the read statement, it will pause and wait for the user to enter the variable value on the keyboard,
After the value is read, the shell program continues to execute.
For example:
#!/bin/sh
echo "Enter your name : "
read name
echo "Hello $name , Have a nice day."
Exit status/Return Value
Exit status of the last command
After each command is executed, a value is returned. This value is called the exit status or return value. If the command is successfully executed, true is returned; otherwise, false is returned. You can use the location parameter $? To check.
In this article, we have made a concise introduction to the script writing of bash shell, but there is actually more shell programming knowledge not mentioned. There are several shell types. bash shell is just one of them. Each shell has a slight difference in syntax. For example, C shell has similar syntax to C. The content introduced here is applicable to various shells.