Variable type, arithmetic operator, conditional test of shell script in Linux

Source: Internet
Author: User
Tags arithmetic arithmetic operators readable terminates valid ssh


Type of variable in bash

Local variable: Valid only for the current shell and not for its child shell

Variable assignment: Name=value

Name= $user

Name= ' command ', name=$ (command): "The Meaning of" and $ () is different.

The following figure can be summarized as follows: if the execution result of a command is assigned to a parameter and contains multiple pairs of inverted quotes nested, the best outer value is $ ()

#!/bin/bash
#
sum=$ (ECHO ' seq $ ' | tr "" + "| BC) ################ #可以正确输出
echo "$ to $ and for: $Sum"

Sum1= ' echo ' seq $ ' | TR "" "+" | BC ' ################ #输出报错
echo "$ to $ and for: $Sum 1"
Root@cenots6.8/testdir #./13sum.sh 1 100
1 to 100 and for: 5050
./13sum.sh:command substitution:line 7:syntax error near unexpected ' | '
./13sum.sh:command substitution:line 7: ' | TR "" "+" | bc
./13sum.sh:line 7:1: Command not found
1 to 100 and for:
Root@cenots6.8/testdir # echo ' seq 1 10 '
1 2 3 4 5 6 7 8 9 10
Root@cenots6.8/testdir # echo ' echo ' seq 1 10 '
Seq 1 10
Root@cenots6.8/testdir # echo $ (echo ' seq 1 10 ')
1 2 3 4 5 6 7 8 9 10
Root@cenots6.8/testdir # echo "Echo ' seq 1 10 '"
Echo 1
2
3
4
5
6
7
8
9
10
Variable reference: $name, ${name}

Show all defined variables: set

Delete variable: unset name

Environment variable: Valid for current shell and its child shell

Variable assignment: Export name=value

Declare-x Name=value

Show all environment variables: export, env, printenv

Delete variable: unset name

The built-in environment variables for bash are: PATH, SHELL, Usre,uid,histsize, Home, PWD, Oldpwd, Histfile, PS1

Local variables: Valid for a fragment of code in the current shell process (usually the function)

Position variables: $ $ ... Representation, which allows the script to represent the first and second arguments in the script code by calling arguments passed in the command line, and shift can replace the argument

Special variables: $?: Judging execution result 0-255

$: script Name

$*: All parameters passed in the command line, and as a whole

$@: All parameters passed by the command line, each parameter as a whole

$#: The total number of parameters passed in the command line, and $@ only in double quotes, you can see the difference from the next script

Root@centos7.2/testdir # cat Arg1.sh arg2.sh
#!/bin/bash
#
Echo 1st is $
Echo 2st is $
echo All args are is "$*"
#!/bin/bash
#
./arg1.sh "$*"

Echo ============i

./arg1.sh "$@"

Echo ==============

Echo $*
Echo $@
Root@centos7.2/testdir #/arg2.sh 1 2 3
1st is 1 2 3
2ST is
All args are are 1 2 3
============i
1st is 1
2ST is 2
All args are are 1 2 3
==============
1 2 3
1 2 3
Read-only variable: read-only variable cannot modify deletion

Variable assignment: readonly name=value, Declare-r name=value

PATH variable definition location:.bash_profile–> $PATH: $HOME/bin

Path= $PATH: $HOME/.local/bin: Hidden directories $HOME/bin–.local/bin centos7 Ordinary users, can be put in a hidden script

When writing scripts, you can write scripts in the bin directory to mkdir/home/bin the relative path.

Source bash.sh can also execute scripts: Its execution process is equivalent to doing it directly in the current shell process, rather than opening a subprocess, all scripts are executed, the echo variable, and the value of the variable is also viewable. (a normal parent process is a variable that cannot view a child process)

Shadow default permission 000 but root is read-writable by Superuser, but if the file does not have X permissions, root cannot execute

Two, arithmetic operator

Arithmetic operators in bash: + 、-、 *,%, * * (squared) Note: "*" to escape "\*" when using expr

To implement arithmetic operations:

Let-var= arithmetic expression

var=$[Arithmetic expression]

var=$ ((arithmetic expression))

var=$ (expr arg1 arg2 arg3) Note: Each parameter is separated by a space

root@cenots6.8 # echo $ (Expr 5 \* 2-1)
9
Declare-i var= Digital

echo ' Arithmetic expression ' | Bc

Random number generator: Random number between echo $[random%50]:0-49

Random numbers between the Echo $[random%50+1]:1-50

$RANDOM: 1-32767

Third, aggregation command

#!/bin/bash

echo xxx; (echo zzz;exit) ############ (): On behalf of the open child Shell,exit exit shell non-current shell

Echo yyy

Four, exit status code

0 represents success, 1-255 represents failure

$? Variable saves the most recent command exit status

We can also specify the status code to exit the program, judging the working state based on the value of the status code, once the Exit command is encountered in the script, the script terminates immediately, terminates, and terminates the exit status depending on the number following the Exit command, and if exit is not executed, the execution status result of the last command of the script is taken.

V. Condition TEST

Testing command: Test [expression]

[$a = $b] to judge a pair [] or two pairs [[]]

[[$a = = $b]] Two equals sign can also

[-f/bin/cat-a-x/bin/cat] a pair [] must be used at this point or it will be an error

Numerical test:

-GT: Greater Than

-ge: greater than or equal

-LT: Less than

-le: less than or equal

-eq: Equal To

-ne: Not equal to

String test:

= =: equal or not

: Greater than (compare ASCLL code)

: Less than

!=: is not equal to

=~: Whether the left string can be matched by the pattern on the right, note: This expression is generally used in [[]];

-Z ' string ': Determines whether a string is empty, or true if it is null

-N "string": Determines whether a string is empty or true if it is not null

Note: When used for string comparisons, the operands should use quotation marks

Existence test:

-A file: Files exist as true or false

-e File: Same-A

Existence and Category testing:

-B File: exists and is block device file blocks

-C file: exists and is a character device file Char

-D file: Exists and is directory file dir

-F file: exists and is a normal file

-H file or-L file: Existing and Symbolic link files

-P file: exists and is a named pipe file

-S file: exists and is a socket file

File permission test:

-R FILE: exists and is readable

-W FILE: Exists and can be written

-X FILE: exists and is executable

File Special permission test:

-G FILE: Exists and has Sgid permissions

-U FILE: Exists and has suid permissions

-K FILE: Exists and has sticky permissions

File size test:

-S FILE: exists, Non-null is true, otherwise false

Whether the file is open:

-T FD:FD indicates whether the file descriptor is open and related to a terminal

-N File: Whether the file was modified automatically after it was last read

-O File: whether the currently active user is a file owner

-G file: Whether the currently valid user is a file group

Binocular test:

File1-ef File2:file1 and FILE2 point to the same inode on the same device

Whether the File1-nt File2:file1 is new to FILE2;

Whether the File1-ot File2:file1 is older than the FILE2;

Combine test conditions:

The first way:

COMMAND1 && COMMAND2 and

COMMAND1 | | COMMAND2 or

! COMMAND Non

such as: [e-file] && [-R File]

The second way:

Expression1-a EXPRESSION2 and

Expression1-o EXPRESSION2 or

! EXPRESSION

First, the operation:

1, write script/root/bin/systeminfo.sh, display the current host system information, including host name, IPV4 address, operating system version, kernel version, CPU model, memory size, hard disk size.

#!/bin/bash
#编写脚本/root/bin/systeminfo.sh, displays the current host system information, including host name, IPV4 address, operating system version, kernel version, CPU model, memory size, hard disk size.
Ipaddr= ' Ifconfig | Sed-n ' 2p ' | Sed ' s@.*inet addr:@@g ' | Sed ' s@bc.*@@ '
sysversion= ' Cat/etc/redhat-release '
Cpu= ' sed-n "5p"/proc/cpuinfo |cut-d:-f2|tr-d ""
meminfo= ' sed-n ' 1p '/proc/meminfo |cut-d:-f2|tr-d ""
fdiskinfo= ' fdisk-l |sed-n ' 2p ' | Grep-o ". *GB" | Sed-r "s@dis.*: @@"
echo "HostName: ' HostName '"
echo "IPAddress: $IPaddr"
echo "Sysversion: $SysVersion"
echo "kernelversion: ' Uname-r '"
echo "CPU: $CPU"
echo "Meminfo: $MemInfo"
echo "Fdiskinfo: $FdiskInfo"

unset ipaddr
Unset sysversion
Unset CPU
Unset Meminfo
Unset Fdiskinfo
Root@cenots6.8/testdir #./systeminfo.sh
hostname:cenots6.8
ipaddress:10.1.249.49
Sysversion:centos Release 6.8 (Final)
Kernelversion:2.6.32-642.el6.x86_64
Cpu:intel (R) Core (TM) I5-5200ucpu@2.20ghz
meminfo:1004136kb
fdiskinfo:128.8 GB
2, write script/root/bin/backup.sh, can realize daily/etc/directory backup to/root/etcyyyy-mm-dd

#!/bin/bash
#编写脚本/root/bin/backup.sh, to enable daily/etc/directory backup to/root/etcyyyy-mm-dd
Dirname= "/root/etc ' Date +%f '"
Cp-a/etc $dirName && echo "Backup succeeded"
Root@cenots6.8/testdir # ls-d ~/etc*; Du-sh ~/etc*
/root/etc2016-08-12
41m/root/etc2016-08-12
3, write Script/root/bin/disk.sh, show the current hard disk partition maximum space utilization value

#!/bin/bash
#编写脚本/root/bin/disk.sh, displays the maximum space utilization value in the current hard disk partition
Use= ' DF | Tr-s "" |cut-d ""-f5|sed-n ' 1!p ' |sort-n|tr-d% |tail-1 ' "
[$Use-GT] && wall disk would be full!
unset use
Root@cenots6.8/testdir #./checkdisk.sh

Broadcast message from root@cenots6.8 (PTS/1) (Fri Aug 12 10:38:52 2016):

Disk is full
4, write Script/root/bin/links.sh, show the host is connected to each remote host IPV4 address and connection number, and by the number of connections from large to small sort

#!/bin/bash
#编写脚本/root/bin/links.sh, displays the number of IPV4 addresses and connections for each remote host that is connecting to this host, sorted by number of connections from large to small
Lincount= ' Netstat-t | grep "TCP" | Tr-s "" | Cut-d ""-f5 | Sed "s@:.*@@" | Sort-n | Uniq-c '
ECHO-E "link Number IP Address"
Echo-e "$linCount"
Root@cenots6.8/testdir #./links.sh
"Number of links IP address"
2 10.1.250.130
5, write a script/root/bin/sumid.sh, calculate/etc/passwd file 10th user and 20th user's ID and

#!/bin/bash
#写一个脚本/root/bin/sumid.sh, calculates the sum of the IDs of the 10th and 20th users in the/etc/passwd file
userid10= "' sed-n ' 10p '/etc/passwd | cut-d:-f3 ' "
userid20= "' sed-n ' 20p '/etc/passwd | cut-d:-f3 ' "
SUMID=$[USERID10+USERID20]
echo "The sum of the IDs of the 10th and 20th users is: $SumId"

Unset USERID10
Unset USERID20
Unset Sumid
Root@cenots6.8/testdir #./sumid.sh
The sum of the IDs of the 10th and 20th users is: 180
6, write a script/root/bin/sumspace.sh, pass two file paths as parameters to the script, calculate all the blank lines in these two files and

#!/bin/bash
#写一个脚本/root/bin/sumspace.sh, pass two file paths as parameters to the script, calculate all the blank lines in these two files and
file1= "' grep" ^$ "$ | Wc-l ' "
File2= "' grep" ^$ "$ | Wc-l ' "
Spacesum=$[file1+file2]
echo "Sum of all blank lines in two files: $SpaceSum"

Unset File1
Unset File2
Unset spacesum
Root@cenots6.8/testdir #./sumspace.sh/etc/profile/etc/fstab
The sum of all blank lines in two files: 12
7, write a script/root/bin/sumfile.sh, statistics/etc,/var,/usr directory, how many levels of subdirectories and files

#!/bin/bash
#写一个脚本/root/bin/sumfile.sh, Statistics/etc,/var, number of first-level subdirectories and files in the/usr directory #
Etcnum= "' ls/etc/| Wc-l ' "
Varnum= "' ls/var/| Wc-l ' "
Usrnum= "' ls/usr/| Wc-l ' "
sumfile=$[$EtcNum + $VarNum + $UsrNum]
echo "The Sumfile: $SumFile"

Unset Etcnum
Unset VarNum
Unset Usrnum
Unset sumfile
Root@cenots6.8/testdir #./sumfile.sh
The sumfile:287
8. Write a script/root/bin/argsnum.sh, accept a file path as an argument, and if the number of arguments is less than 1, prompt the user to "at least one parameter" and exit immediately; If the number of parameters is not less than 1, the number of blank lines in the file pointed to by the first argument is displayed

#!/bin/bash
#写一个脚本/root/bin/argsnum.sh, accept a file path as an argument, and if the number of arguments is less than 1, prompt the user to "at least one parameter" and exit immediately; If the number of parameters is not less than 1, the first parameter is displayed
The number of blank lines in the file to which the number points
[[$#-lt 1]] && echo "should at least give a parameter" | | echo "Spacenum:" grep "^$" $ | Wc-l ' "
Root@cenots6.8/testdir #./argsnum.sh
At least one argument should be given
Root@cenots6.8/testdir #./argsnum.sh/etc/profile
Spacenum:11
9, write a script/root/bin/hostping.sh, accept a host of IPV4 address as a parameter, test is connected. Prompts the user for "access to the IP address" if it can ping, and prompts the user "This IP address is inaccessible" if it is not ping-pass

#!/bin/bash
#
PING-C1-W2 $ &>/dev/null && echo "This IP address accessible" | | echo "This IP address is inaccessible"
Root@cenots6.8/testdir #./hostping.sh 10.1.249.48
The IP address can be accessed
Root@cenots6.8/testdir #./hostping.sh 10.1.249.4
This IP address is not accessible
10, Chmod-rw/tmp/file1, write script/root/bin/per.sh, to determine whether the current user to/tmp/fiile1 file is unreadable and not writable

#!/bin/bash
#
[-r/testdir/file1-a-w/testdir/file1] && echo "' whoami ' readable and writable" | | echo "' WhoAmI ' is not readable and writable"
Root@cenots6.8/testdir #./per.sh
Root can be read and writable
Tom@cenots6.8/testdir #./per.sh
Tom is not readable and writable.
11, Script/root/bin/nologin.sh and login.sh, to achieve the prohibition and allow ordinary user login system.

#!/bin/bash
#编写脚本/root/bin/nologin.sh and login.sh, to achieve the prohibition and allow ordinary user login system.
[!-f/etc/nologin] && echo "Ordinary users can no longer login system" && Touch/etc/nologin

[-f/etc/nologin] && echo "Ordinary users have been able to login system" && Rm-rf/etc/nologin
Root@cenots6.8/testdir #/login.sh ######################## #禁止普通用户登陆
Ordinary users can no longer log on to the system
[c:\~]$ ssh tom@10.1.249.49

Connecting to 10.1.249.49:22 ...
Connection established.
To an escape to the local shell, press ' ctrl+alt+] '.

Connection closed by foreign host.

Disconnected from remote host (10.1.249.49:22) at 12:09:27.

Type ' help ' to the learn how-to-use Xshell prompt.
Root@cenots6.8/testdir #/login.sh ######################### #允许普通用户登陆
Ordinary users can already log on to the system
[c:\~]$ ssh tom@10.1.249.49

Connecting to 10.1.249.49:22 ...
Connection established.
To an escape to the local shell, press ' ctrl+alt+] '.

tom@cenots6.8 ~ #
12, write a script/root/bin/hostping.sh, accept a host of IPV4 address as the parameter, first judge whether the qualified IP, no, hint IP format illegal and exit, is, test is connected. Prompts the user for "access to the IP address" if it can ping, and prompts the user "This IP address is inaccessible" if it is not ping-pass

#!/bin/bash
#
echo "$" | Grep-e-qo ' ([0-9]|[ 1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]) \.) {3} ([0-9]| [1-9] [0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]) ' && (ping-c1-w2 $ &>/dev/null && echo "This IP address can be accessed" | | echo "No access to this IP address") | | echo "This IP address is illegal"; Exit 1
Root@cenots6.8/testdir #./hostping.sh
The IP address is illegal
Root@cenots6.8/testdir #./hostping.sh 10.1.249.49
The IP address can be accessed
Root@cenots6.8/testdir #./hostping.sh 192.192.192.192
The IP address cannot be accessed
13, calculate the value of 1+2+3+...+100

#!/bin/bash
#
Num= ' echo {1..100} | TR "" "+" | BC '
echo "$ to $ and for: $Num"
Root@cenots6.8/testdir #./13sum.sh
To and for: 5050
#!/bin/bash
#
sum=$ (ECHO ' seq $ ' | tr "" + "| bc
echo "$ to $ and for: $Sum"
Root@cenots6.8/testdir #./13sum.sh 1 100
1 to 100 and for: 5050
14. Calculate the sum of all the numbers from the first parameter a of the script, to the second parameter B, to determine if B is greater than a, whether to prompt for errors and exit, is calculated

#!/bin/bash
#计算从脚本第一参数A开始, to the sum of all the numbers in the second argument B, to determine if B is greater than a, not to prompt for errors, and to exit, is calculated
sum=$ (echo ' seq $ ' | tr "" + "| BC)
[$1-lt $] && echo $ $ and for: $Sum | | echo "cannot be greater than $ $"; exit 1
root@cenots6.8 /testdir #./14s um.sh 1
1 to 100 of the and is: 5050
root@cenots6.8 /testdir #/14sum.sh 1
100 cannot be greater than 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.