Shell Programming notes (1)

Source: Internet
Author: User
Tags arithmetic stdin

Shell Programming:

Compilers, interpreters

Programming languages: Machine language, assembly language, advanced languages

Static language: Compiled language
Strongly typed (variable)
Convert into executable format in advance
C, C + +, JAVA, C #



Dynamic language: Interpreted language, on the fly
Weak type
Edge Interpretation Side Execution
PHP, SHELL, Python, Perl


Process oriented: Shell, C
Object-oriented: JAVA, Python, Perl, C + +

Variables: Memory space, naming

Memory: Addressable storage unit

Process:
1+100:
1+1000000
1

Variable type: Determine the storage format and length of the data in advance
Character
Numerical
Integral type
Float type: 11.23, 1.123*10^1, 0.1123*10^2
2013/10/10, 64bit
99999:24bit,
True, False


Logic: 1+1>2
Logical operations: With, or, non-, XOR, or
1: True
0: Fake

1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
1 & 1 = 1

Or:

Non -:
! true = False
! False = True

Shell: Weakly typed programming language

Strong: Variables must be declared beforehand and even initialized before they are used;
Weak: variable time declaration, even the type is not differentiated;

Variable assignment: Var_name=value



Bash Variable type:
Environment variables
Local variables (local variables)
Positional variables
Special variables

Local variables:
Set Varname=value: scope for the entire bash process;

Local variables:
Local Varname=value: Scope is the current code snippet;

Environment variable: scope is the current shell process and its child processes;
Export Varname=value
Varname=value
Export VARNAME
Export

Positional variables:
$, $, ...

Special variables:
$?: The execution status return value of the previous command;

program execution, there may be two types of return values:
Program execution Results
Program Status return codes (0-255)
0: Correct execution
1-255: Error execution, 1,2,127 system reservation;

Output redirection:
>
>>
2>
2>>
&>

Undo Variable:
Unset VARNAME

To view variables in the shell:
Set

To view environment variables in the current shell:
Printenv
Env
Export

Script: Command stack, according to the actual needs, combined with the command flow control mechanism to implement the source program

Shebang: Magic number
#!/bin/bash
# comment lines, do not execute



/dev/null: Software device, bit bucket, data black hole


The script starts a child shell process when it executes;
Scripts that are started on the command line inherit the current shell environment variable;
Scripts that are automatically executed by the system (non-command-line startup) require a self-defined environment variable;



Exercise: Write a script to complete the following tasks
1, add 5 users, User1,..., User5
2, each user's password with the user name, and requirements, add the password after completion does not display the passwd command execution results information;
3, each user added after the completion, to show that the user has been successfully added;
Useradd user1
echo "User1" | passwd--stdin user1 &>/dev/null
echo "Add user1 successfully."


Condition Judgment:
If the user does not exist
Add user, give password and display add success;
Otherwise
Show if no already in, no add;

How do I make conditional judgments in bash?
Condition Test Type:
Integer test
Character test
File test

Expressions for Conditional tests:
[Expression]
[[Expression]]
Test expression

Integer comparison:
-EQ: Tests whether two integers are equal, such as $A-eq $B
-ne: Test whether the two integers are unequal, unequal, true, equal, false;
-GT: Tests whether one number is greater than the other, greater than, true, or false;
-LT: Tests whether one number is less than the other, less than, true; otherwise, false;
-ge: greater than or equal to
-le: Less than or equal to

The logical relationship between commands:
Logic and: &&
When the first condition is false, the second condition is no longer judged and the final result is already there;
When the first condition is true, the second condition must be judged;
Logical OR: | |

If the user User6 does not exist, the user is added User6
! ID USER6 && useradd user6
ID User6 | | Useradd User6

If the number of rows in the/etc/inittab file is greater than 100, a large file is displayed;
[' Wc-l/etc/inittab | cut-d '-f1 '-gt] && echo "Large file."

Variable name:
1, can only contain letters, numbers and underscores, and can not start with a number;
2, should not be the same as the existing environment variables in the system;
3, it is best to see the name and know righteousness;

If the user exists, the user is already present, otherwise the user is added;
ID user1 && echo "user1 exists." | | Useradd user1

If the user does not exist, add; otherwise, show that it already exists;
! ID user1 && Useradd user1 | | echo "User1 exists."

If the user does not exist, add and give the password, otherwise, show that it already exists;
! ID user1 && useradd user1 && echo "user1" | passwd--stdin User1 | | echo "User1 exists."


Practice, write a script to complete the following requirements:
1, add 3 users user1, User2, User3; But first to determine whether the user exists, does not exist and then add;
2, added after the completion, the display has added a total of several users, of course, can not be included because of pre-existing and not added;
3, finally shows how many users on the current system;



Practice, write a script to complete the following requirements:
Given a user:
1, if its UID is 0, this is displayed as an administrator;
2, otherwise, it is displayed as a normal user;

If the UID is 0;
Show as Administrator
Otherwise
Show as normal user

Name=user16
Userid= ' Id-u $NAME '
If [$USERID-eq 0]; Then
echo "Admin"
Else
echo "Common user."
Fi



Name=user16
If [' id-u $NAME '-eq 0]; Then
echo "Admin"
Else
echo "Common user."
Fi


If ID $NAME; Then

Exercise: Write a script
Determine if there is a user's default shell for bash on the current system;
If so, the number of such users is displayed, otherwise, no such user is shown;
grep "bash$"/etc/passwd &>/dev/null
Retval=$?
If [$RETVAL-eq 0]; Then

If grep "bash$"/etc/passwd &>/dev/null; Then

Hint: "Reference" the execution result of a command to use a command reference; for example: resaults= ' wc-l/etc/passwd | cut-d:-f1 ';
Using the execution status result of a command, it must not be referenced to execute the command directly, for example: if ID user1 the ID command in a sentence must not be quoted;
If you want to assign the result of a command to a variable, use a command reference, such as userid= ' Id-u user1 ';
If you want to save the execution status result of a command, and as a condition for the success or absence of a command execution, you need to execute this command before referencing its status results, such as
Id-u user1
Retval=$?
This sentence must not be written as retval= ' Id-u user1 ';


Exercise: Write a script
Determine if there is a user's default shell for bash on the current system;
If so, displays one of the user names; otherwise, no such user is displayed;

Exercise: Write a script
Given a file, such as/etc/inittab
Determine if there is a blank line in this file;
If so, the number of blank lines is displayed, otherwise, no blank lines are displayed.
#!/bin/bash
A= ' grep ' ^$ '/etc/inittab | Wc-l '
If [$A-gt 0]; Then
echo "$A"
Else
echo "Meiyoukongbaihang"
Fi
--by Zhang Shuai

#!/bin/bash
File=/etc/inittab
if [!-e $FILE]; Then
echo "No $FILE."
Exit 8
Fi

If grep "^$" $FILE &>/dev/null; Then
echo "Total Blank lines: ' grep" ^$ "$FILE | Wc-l '. "
Else
echo "No blank line."
Fi

Exercise: Write a script
Given a user, determine if the UID is the same as the GID
If it does, the user is displayed as "good guy", otherwise the user is shown as "bad guy".
#!/bin/bash
Username=user1
Userid= ' Id-u $USERNAME '
Groupid= ' Id-g $USERNAME '
If [$USERID-eq $GROUPID]; Then
echo "good guy."
Else
echo "bad guy."
Fi

Further requirements: Do not use the ID command to obtain its ID number;

#!/bin/bash
#
Username=user1
if! grep "^ $USERNAME \>"/etc/passwd &>/dev/null; Then
echo "No such User: $USERNAME."
Exit 1
Fi

Userid= ' grep ' ^ $USERNAME \> "/etc/passwd | cut-d:-f3 '
Groupid= ' grep ' ^ $USERNAME \> "/etc/passwd | cut-d:-f4 '
If [$USERID-eq $GROUPID]; Then
echo "good guy."
Else
echo "bad guy."
Fi






Exercise: Write a script
Given a user, get their password warning period;
And then determine whether the user password period is less than the warning period;
Tip: The calculation method, the maximum period of use minus the number of days that have been used is the remaining period of use;

If it is less than, "Warning" is displayed; otherwise, "OK" is displayed.

Rounding: Discard everything after the decimal point

#!/bin/bash
w= ' grep ' Student '/etc/shadow | cut-d:-f6 '
s= ' Date +%s '
t= ' expr $S/86400 '
L= ' grep ' ^student '/etc/shadow | cut-d:-f5 '
n= ' grep ' ^student '/etc/shadow | cut-d:-f3 '
sy=$[$L-$[$T-$N]

If [$SY-lt $W]; Then
Echo ' Warning '
Else
Echo ' OK '
Fi

--by Donglidong


Exercise: Write a script
Determines whether the total entry for history commands in the command history is greater than 1000, or if greater than, displays "Some command will gone." Otherwise, "OK" is displayed.


How to perform arithmetic operations in the shell:
A=3
B=6
1. Let arithmetic operation expression
Let c= $A + $B
2. $[arithmetic operation expression]
c=$[$A + $B]
3, $ (arithmetic operation expression)
c=$ (($A + $B))
4, expr arithmetic expression, the expression in the operands and operators to have a space between, and to use the command reference
c= ' expr $A + $B '



Conditional judgment, control structure:

Single Branch if statement
if judgment condition; Then
Statement1
Statement2
...
Fi

Two-branch if statement:
if judgment condition; Then
Statement1
Statement2
...
Else
Statement3
Statement4
...
Fi

Multi-Branched if statement:
if judgment condition 1; Then
Statement1
...
Elif judgment Condition 2; Then
Statement2
...
Elif judgment Condition 3; Then
Statement3
...
Else
Statement4
...
Fi



Test method:
[Expression]
[[Expression]]
Test expression

There are three common conditions tested in bash:
Integer test:
-gt
-le
-ne
-eq
-ge:
-LT:

int1=63
int2=77
[$INT 1-eq $INI 2]
[[$INT 1-eq $INT 2]]
Test $INT 1-eq $INT 2

File test:
-e file: Test files exist
-F File: Test files are normal files
-D FILE: Tests whether the specified path is a directory
-R File: Tests whether the current user has read access to the specified file;
-W
-X

[-e/etc/inittab]
[-x/etc/rc.d/rc.sysinit]

Exercise: Write a script
Given a file:
If it is an ordinary file, it is displayed;
If it is a directory, it is also displayed;
Otherwise, this is a document that cannot be recognized;



Defining script Exit Status codes

Exit: Exit Script
Exit #
If the script does not explicitly define the exit status code, then the exit code of the last command executed is the exit status code of the script;


Test the script for syntax errors:
Bash-n Script

Bash-x Script: Stepping





Types of Bash variables:
Local variables (local variables)
Environment variables
Positional variables:
$, $, ...
Shift: kicks off parameters


Special variables:
$?
$#: Number of parameters
$*: Parameter list
[email protected]: parameter list

Shift one time to kick off multiple



./filetest.sh/etc/fstab/etc/inittab
$:/etc/fstab
$:/etc/inittab

Exercise: Write a script
can accept a parameter (file path)
Decision: This parameter displays "OK" if it is a file that exists. Otherwise, "No such file" is displayed.

Exercise: Write a script
Pass two parameters (integers) to the script;
Show the sum of the two, the product;
#!/bin/bash
#
If [$#-lt 2]; Then
echo "Usage:cacl.sh ARG1 ARG2"
Exit 8
Fi

echo "The sum is: $[$1+$2]."
echo "The prod is: $[$1*$2]."


Exercise: Write a script to complete the following tasks
1, use a variable to save a user name;
2, delete the user in this variable, and delete their home directory;
3, display the "User Delete complete" class information;





Bash:

Reference variable: ${varname}, parentheses can sometimes be omitted.




Integral type, 8bit:256
0-255, overflow


Variable:
1,10000


10:16bit
10:1010, 8bit

Shell Programming notes (1)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.