Linux Learning 21-shell Programming Basics

Source: Internet
Author: User
Tags php programming ssh

Shell Programming Basics

The shell is a program written in C that is a bridge for users to use Linux. The shell is both a command language and a programming language. A Shell is an application that provides an interface through which users access the service of the operating system kernel. Shell scripts (shell script), a scripting program written for the shell

Shell programming is like Java and PHP programming, as long as there is a text editor that can write code and a script interpreter that can explain execution.

    1. Shell types in Linux (type of Shell interpreter)

[Email protected] ~]# Cat/etc/shells

/bin/sh

/bin/bash

/sbin/nologin

/bin/dash

/bin/tcsh

/bin/csh

    1. Shell script basic rules and execution

In the shell script file, the first line indicates which Shell interpreter to use

#!/bin/bash #指定shell解释器为bash

The beginning of the second line is a number of commands

Example: a simple shell script

#!/bin/bash

Pwd

Mkdir-p test{1..10}

Touch test{1..10}/oldboy{1..10}

Ifconfig eth0|awk-f "[:]+" ' Nr==2{print $4} ' >>ip.txt

echo "Hello world!"

PARTED/DEV/SDA P

How shell scripts are executed

Method 1, bash + script name

Method 2, SH + script name

You can use the parameter sh-x to enter debug debug mode to view the execution process

Method 3,./+ script Name

Method 4, directly using the absolute path of the script can be

    1. Shell Script Reference variable

3.1 If the shell script is all commands, flexibility will be poor, can be implemented by reference variables, variables can be directly assigned to the value can also be executed by the command to assign a value

Naming rules for variables:

Cannot have the same name as the system already has (multiple uppercase letters) and cannot start with a number

Can only be underlined, the letter begins, the middle of the variable allows a number

cannot be the same as the current environment variable for the system

3.2 Execute Command ENV view current environment variables

View only system all environment variable name env|awk-f "=" ' {print '} '

Call environment variable echo% variable name%

3.3 Special environment variable $PS1 can customize terminal command prompt

echo $PS 1

Ps1= ' [\[email protected]\h \w]\$ '

Ps1= ' [\[\e[31;1m\]\t\[\e[0m\] \[email protected]\h \w]# '

[Email protected] ~]# echo $PS 1

[\[email protected]\h \w]\$

[[email protected] ~]# ps1= ' [\[\e[31;1m\]\t\[\e[0m\] \[email protected]\h \w]# '

[20:56:21 [email protected] ~]#

3.4 Referencing variable instances

#!/bin/bash

Name= ' hostname '

echo "Your current host name is $name"

ip= ' Ifconfig eth0|awk-f "[:]+" ' Nr==2{print $4} '

echo "Your current IP address is $ip"

Ks_line= ' Cat/root/anaconda-ks.cfg|wc-l '

echo "KS file detection total $ks_line line"

Rpm_count= ' Rpm-qa|wc-l '

echo "RPM packet detection Total $rpm_count"

Ip_r= ' Route-n|awk ' $1== "0.0.0.0" && $2== "10.0.0.254" ' |wc-l '

echo "Gateway detection pass value is $ip_r"

log_file= ' Wc-l/tmp/install.log|wc-l '

echo "Install log detection pass value is $log_file"

Se_status= ' Sestatus|awk ' {print $NF} ' #sestatus查看selinux状态

echo "SELinux status Check status is $se_status"

ssh_config= ' Cat/etc/ssh/sshd_config|wc-l '

echo "SSH optimized detection pass value is $ssh_config"

    1. For loops in shell scripts

Example 1: If you need to create 10 users in bulk and generate a random password and modify it, and redirect to a file to display the user name and password

#!/bin/bash

For i in ' seq-f stu%g 1 5 '

Do

Useradd $i; pass= ' date +%n|md5sum|cut-c 1-8 '; Echo $i: $PASS >> passwd.txt;echo $PASS |passwd--stdin $i

Done

Example 2: Using a For loop to optimize the boot entry

#!/bin/bash

For i in ' Chkconfig|grep ' ^[a-z] ' |awk ' {print '} ' |sed ' $d '; #先关闭所有开机启动项

Do

Echo $i

Chkconfig $i off

Done

For j in Network Crond sysstat Rsyslog sshd; #再开启需要的启动项

Do

Chkconfig $j on

Done

Example 3: Using a For loop, change the txt ending file to txt

#!/bin/bash

For i in ' LS *.txt '

Do

Old_name= ' echo $i |awk-f. " ' {print '} '

MV $i ${old_name}. Txt

Done

Example 4: Nesting for loops

Batch creation of 10 directories starting with Oldboy, and creating 10 files larger than 300k in the directory requires the DD command to create a file

#!/bin/bash

mkdir oldboy{1..10}

For n in oldboy{1..10}

Do

For M in test{1..10}

Do

DD If=/dev/zero of=${n}/$m bs=101k count=3

Done

Done

5. If judgment statement in shell script

Parameters related to judgment

GT Greater than

EQ equals

LT is less than

GE is greater than or equal

Le is less than or equal

-O Logic or

-Z to determine if the input is empty

-N to determine if the input is not empty

Example 1: Guessing a number game

#!/bin/bash

Num1= ' echo $RANDOM *35/32767+1|bc '

Read-p "Please enter a number:" Num2

echo $num 1

If [$num 1-gt $num 2];then

Echo, "you guessed it's small."

elif [$num 1-eq $num 2];then

echo "Congratulations, you guessed it!"

Else

Echo, "You're a big guess."

Fi

Example 2: Use a fixed usage read-p ' * * * ' str to read what the user entered after the execution of the shell and determine if it is empty

#!/bin/bash

Read-p ' Please enter a string: ' str

Echo $str

If [-Z $str];then

echo "The content you entered cannot be empty!"

Fi

    1. Shell Script production case

Regularly pack backups, keep the last week's backup files, and keep the past files for Saturday

Mkdir-p/service/scripts

cd/service/scripts/

Note: There is a requirement to back up seven days of content per Saturday, you can choose in Saturday just transition to Sunday date is the early Sunday, so that the content of the Saturday backup is more complete, the backup content is Saturday, then the name of the compressed package needs to use the date command's-D yesterday parameter

#!/bin/bash

# # #beifen

w= ' Date +%w '

If [$W-eq 0];then

Tar zcvf/backup/6_etc_ ' date-d yesterday +%f '. tar.gz/etc

Else

Tar zcvf/backup/etc_ ' date-d yesterday +%f '. tar.gz/etc

Fi

# # #qingli

Find/backup-type f-name "*.tar.gz"-mtime +7|grep-v ' 6_etc_ ' |xargs rm–rf

Write scripts to test, modify current time and backup, last sync time

#!/bin/bash

For N in ' seq-w 24 '

Do

Date-s "201804$n";/bin/bash/service/scripts/backup.sh

Done

Ntpdate ntp1.aliyun.com

and write the script to the scheduled task.

#on Time Backup

    1. XX * * */bin/bash/service/scripts/backup.sh &>/dev/null

For more information about Shell scripting, refer to the

Http://www.runoob.com/linux/linux-shell.html

Bo Master original articles, reproduced please be sure to indicate the source

Linux Learning 21-shell Programming Basics

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.