Home > Operation and Maintenance > Linux Operation and Maintenance > What is a shell? Introduction to common types of shells

What is a shell? Introduction to common types of shells

零下一度
Release: 2017-06-30 15:50:18
Original
7026 people have browsed it
1. Introduction
2. read
3. Computational tools
4. if/then structure
5.while loop
6.for loop
1. Introduction
1. What is shell
Shell is the interface for interaction between users and the system. The shell is a command interpreter and a high-level programming language
2. Common types of shell
Bourne Shell (/usr/bin/sh or / bin/sh)
Bourne Again Shell (/bin/bash)
C Shell (/usr/bin/csh)
K Shell (/usr/bin/ksh )
Shell for Root (/sbin/sh)
Among them: Bash is widely used in daily work; At the same time, Bash is also the default Shell for most Linux systems ;
3. Shell limitations
1.1. Tasks that require a large amount of resources, especially those that require high execution speed
1.2. Involving a lot of mathematical calculations
1.3. Key applications (databases, websites, etc.)
1.4. Applications for designing graphics or GUI
1.5. Need direct access to hardware
1.6. Develop closed source applications (compared to open source)
4. Basics
File system: The Linux file system is a hierarchical organizational structure that includes directories and files. The one at the top is called the root directory (root directory), which is represented by a slash /
Directory: It is a file containing directory entries. Each directory entry contains the file name
File name: The contents of the directory are called directory entries, and the directory entries contain In file names, only two characters are not allowed to appear in file names: slash and null character (ASCII value is 0). Slash is used to separate file names in the path, and null character is used to indicate the end of the path. The length of the file name can usually reach 255 characters
Path: A series of file names connected together and separated by slashes is called a path. The path is used to indicate the location of the file; The path starting with a dash is called an absolute path, otherwise it is a relative path. The relative path is relative to the current working directory
Return code: All commands have a return value, represented by an integer between 0-255; a script is a command, and it also has a return value. In addition, the functions in the script also have return values
The formal way to exit a script is to explicitly use the command exit [code] to exit, such as: exit 0; exit $?
2. read
1. Definition
read is a buildin command, which mainly completes the assignment of parameters, similar to scanf in C language;
Others Not only can variables be assigned, but arrays can also be assigned;
The input is not only the screen, but also the file descriptor
2. Practical operation
# read a --Input a string and assign the string to variable a; # echo $a
hello world!!
# read name sex age --Assign values ​​to three variables at the same time , the input separator defaults to the space character
zhangsan male 50
# unset name sex age --delete the variable
# IFS=';' --change the input of read Change the delimiter to ';'
# vim test.sh
#!/bin/bash
prompt="Please enter your name:"
read -p "$prompt" name
echo "Greetings $name"
3. Computational tools
1. Simple mathematical operations
# echo $((1+2**2-3*4/5%6)) --Output the calculation results to the screen
# a=$((1+2**2-3*4/5%6)) --Assign the calculation result to the variable a
# ((a=1+2**2-3* 4/5%6)) --Same as above
# echo "scale=3;10/3" | bc --bc calculator; keep three decimal places
# echo "2 ^10" | bc --bc calculator; calculate 2 raised to the 10th power
# awk 'BEGIN{print 1/3}' --awk calculate
2, get Random number
# od -N4 -tu4 /dev/urandom | sed -n '1s/.* //p' --Get a 7-digit number
# od -Ad -w24 -tu4 /dev/urandom --Get random numbers
# od -tu8 /dev/urandom --Get random numbers
# od -tu8 /dev/urandom | sed -r 's/^[0-9]+\s+//' | sed -r 's/\s+/\n/g' |cut -b1- 8 |sed -r -n '/^.{8}$/p' | sed 's/^/186/' |head -n5000 |vi - --Get 10,000 phone numbers
# od -N40000 -tu4 /dev/urandom | sed -r 's/^[0-9]+(\s+)?//' | sed -r 's/\s+/\n/g' | grep -vE '^\s*$' > 10k_random --Generate 10,000 random numbers
# sed -r -n '/^.{8}$/p' 10k_random | head -n 100000 | sed ' s/^/186/' > phone_num
3. Get the number sequence
# seq 10 --get 1 to 10
# seq 1 2 10 --Get 1 to 10, step size is 2
# seq 10 100 --Get 10 to 100
# seq 10 -1 1 --Reverse order, 10 to 1
4. if/then example
1. Determine whether the character "a" is equal to "A"
# vim test.sh
#!/bin/bash
if [[ "a" = "A" ]]; then
if [ "a" = "A" ]; then
 echo "a equals A"
else
 echo "a no equals A"
fi
2. Determine whether /root/test/test.sh exists and has executable permissions
# vim test.sh
#!/bin/bash
if test -x /root/test/test.sh;then
echo "/root/test /test.sh is executable"
fi
#3. Determine whether the root user exists in the system
# vim test. sh
#!/bin/bash
if grep -E --color=auto ^root: /etc/passwd; then
echo "user root exists"
fi
4. Determine the file type
# vim test.sh
#!/bin /bash
function isSymbolicLink() {
 file=$1
 flag=$(ls -ld $file | cut -b1)
 test "$flag" = "1"
 return $?
}
file=$1
if isSymbolicLink $file; then
echo "Symbolic Link"
elif test -d $file; then
echo "Directory file"
elif test -f $file; then
echo "Regular file"
elif test -b $file; then
echo "Block special"
elif test -c $file; then
echo "Character special"
elif test -p $file; then
echo "Named pipe"
elif test -S $file; then
echo "Socket"
else
echo "Unkown"
fi
#5. Determine the size of the input number
# vim test.sh
#!/bin/bash
num=$1
if test "$num" -lt 10 ;then
 echo "Small number"
elif test "$num" -lt 20;then
echo "Middle number"
elif test "$num" -lt 30;then
echo " Large number"
else
echo "Extra large number"
fi
6. Get a number from the standard input and calculate it according to its size Output the specified string
# vim test.sh
#!/bin/bash
echo -n "Enter a number: "
read num
if [ "$num" -lt 100 ]; then
echo "Less than 100"
elif [ "$num" -ge 100 -a "$num" -lt 200 ]; then
echo "Greater than or equal to 100 and less than 200"
elif [ "$num" -ge 200 -a "$num" -lt 300 ]; then
echo "Greater than or equal to 200 and less than 300"
else
echo "Other numbers"
fi
5. wihle loop
1. Understanding
Test the return code of a command after the while keyword. When the condition is true, the program reads into the while loop body Instructions; 0 is true. The loop body is as follows:
while [] --while then run the [ ] command and test the return code of the [ ] command
cat /filename | while read line    --While, run the read command later and test the return code of the read command
do
......
done
2. Loop control statement
continue --terminate the current loop and start the next one
break --terminate the current loop and exit the loop body
exit -- Terminate the current script
3, Example
# vim test.sh --Distinguish the difference between continue and break
#!/bin/bash
while true
do
sleep 1
echo test
continue/break
echo
done
# vim test.sh --Distinguish the difference between break and exit
#!/bin/bash
while test -e /data/test/test.sh
do
echo "exists"
sleep 1
break/exit
done
echo "loop end"
# vim test.sh --Look for the path we gave until we find it
#!/bin/bash
if test $# -ne 1;then
echo "wrong paraneter" >&2
exit
fi
path=$1
while test ! -e "$path"
do
sleep 1
echo "don't found!!!"
done
echo "found"
# vim test.sh --The script runs for the specified time and exits when the time is up; the unit is s
#!/bin/ bash
if test $# -ne 1;then
echo "Usage: $(basename $0) TIME" >&2
exit 1
fi
timeLength=$1
beginTime=$(date +%s)
endTime=$(( $beginTime + $timeLength ))
- -------------------------------------------------- ------
while test $(date +%s) -lt "$endTime"
do
echo "processing...."
sleep 1
done
-------------------------------- --------------------------
while true
do
if test $(date +%s) -ge "$endTime";then
break
fi
echo "processing...."
sleep 1
done
-------------------------------------------------- ----------
echo "time out"
# vim test.sh --Loop to read each line of the file and calculate the value of each line Number of characters
#!/bin/bash
file=$1
----------------- ----------------------------------------
totalLines=$( wc -l < $file)
line=1
while test $line -le $totalLines
do
lineData=$(sed - n "${line}p" $file)
len=$(echo -n $lineData | wc -c)
echo "line ${line}: $len"
line=$(( $line + 1 ))
done
--------------------- ----------------------------------
line=1
while read lineData
do
len=$(echo $lineData | wc -c)
echo "line ${line}: $len "
line=$(( $line + 1 ))
done < $file
--------- ------------------------------------------------
# vim test.sh -- Print out 10 lines of hello world; <(seq 10) is equivalent to a file path; called process replacement
#!/ bin/bash
while read num
do
echo "hello world"
done < <(seq 10)
--------------------------------------------- --------------
n=1
while [ $n -le 10 ]
do
echo "hello world"
n=$((n+1))
done
---------- --------------------------------------------------
# vim test.sh --Create an endless loop, requiring the loop to terminate automatically after running for 1 minute
#!/bin/bash
start_time =$(date +%s)
while true
do
cur_time=$(date +%s)
test $((cur_time - start_time)) -ge 10 && break
time=$((cur_time - start_time))
echo "time is $time..."
sleep 1
done
# vim test.sh --First use a while loop to create 100 .txt files; then change the suffix names of all files to .html
#!/bin/bash
count=100
------------------------ --------------------------------
seq $count | while read i
do
touch ${i}.txt
done
ls -1 *.txt | while read oldname
do
newname=$(echo $oldname | sed 's/.txt$/.html/')
mv $oldname $newname
done
--------------------------------------------- ---------------
while read i
do
touch ${i}.txt
done < <( seq $count )
while read oldname
do
newname=$(echo $oldname | sed 's/ .txt$/.html/')
mv $oldname $newname
done < <(ls -1 *.txt )
# vim test.sh --Calculate the sum of even numbers within 1000; pipes cannot be used because pipes will generate child processes
#!/bin/bash
sum=0
while read num
do
sum=$(( $sum + $num ))
done < <(seq 2 2 998)
echo "sum: $sum "
# vim test.sh --Add 100 email users in batches, the usernames are u1 to u100, the password is abc, the login shell is /sbin/nologin, and they only belong to the email group
#!/bin/bash
password=abc
group=email
grep -Eq "^${group}:" /etc/group || groupadd $group
while read i
#do
useradd u${i} -N -g $group -s /sbin/nologin
passwd u${ i} --stdin <<< "$password"
done < <(seq 100)
# vim test.sh --Batch delete just created 100 mail users
#!/bin/bash
while read i
do
userdel -r u${i}
done < <(seq 100
6. for loop
In a series of items separated by delimiters In the string, one of them is taken at a time in order. When it is finished, the loop ends
The string taken out each time will be saved in a variable, which can be used in the loop body
Strings separated by delimiters can be provided through the following methods:
1. Manually enter the string for looping the specified number of times
# vim test .sh
#!/bin/bash
for i in 1 2 3
do
echo $i
don
2. Provide the string by the variable
# vim test.sh
#!/bin/bash
FILES="/bin/bash /bin/ls /bin/cat"
for file in $FILES
do
echo $file
done
3. String generated by the program
# vim test.sh
#!/bin/bash
for n in $(seq 11)
do
 echo $n
done
4、 Generated by shell expansion, looping files in the directory
# vim test.sh
#!/bin/bash
for f in / etc/init.d/*
do
echo $f
done
# vim test.sh
5. Print out the file names of all files starting with loop under /dev
# vim test.sh
#!/bin/bash
for file in /dev/loop*
do
echo $(basename $file)
done
6. Calculate the number of 1000 The sum of even numbers within
# vim test.sh
#!/bin/bash
sum=0
for number in $ (seq 2 2 998)
do
 sum=$(( $sum + $number ))
done
echo "total: $sum "
7. Add 100 email users in batches. The user names are u1 to u10, the password is abc, the login shell is /sbin/nologin, and they only belong to the email group
# vim test.sh
#!/bin/bash
function checkGid() {
gid=$1
if ! grep -qE " ^$gid:" /etc/group; then
groupadd $gid
fi
}
function isRoot() {
id=$(id | awk -F "[=(]" '{print $2}')
if test "$id" -ne 0; then
echo "must be root" >&2
exit 1
fi
}
count=10
namePrefix=u
password=abc
shell=/sbin/nologin
gid=email
isRoot
checkGid $gid
for num in $(seq $count)
do
name=${namePrefix}${num}
useradd $name -s $shell -g $gid &> /dev/null
if test $? -ne 0; then
echo "failed to create $name" >&2
else
echo "created successfully -- $name"
echo "$password" | passwd --stdin $name &> /dev/null
if test $? -ne 0; then
echo "failed to change password for $name" >&2
else
echo "password changed successfully -- $name"
fi
fi
done
8、获取局域网内所有电脑的IP 和MAC 地址的对应表
# vim test.sh
#!/bin/bash
ipPrefix=192.168.1.
startIp=1
endIp=254
for num in $(seq $startIp $endIp)
do
ip=${ipPrefix}$num
ping -W1 -c1 $ip &>/dev/null &
done
wait
arp -n | sed '/incomplete/d' | awk '{print $1,$3}'| cat | sort -n -t '.' -k4,4 | column -t
9. Print out the multiplication table
# vim test.sh
#!/bin/bash
for row in $ (seq 9)
do
for col in $(seq $row)
do
echo -n "${col}x${ row}=$(( $col * $row )) "
done
echo
done | column -t
10、 Simple calculator
#!/bin/bash
varnum=3
if test "$#" -ne "$varnum"; then
echo "wrong argument" >&2
exit 1
fi
num1=$1
num2=$3
operator=$2
if test "$operator" = "x";then
operator="*"
fi
if test "$operator " = "/" -a "$num2" = 0; then
echo "division by 0" >& 2
exit 1
fi
result=$(( $num1 $operator $num2 ))
echo "$result"
Note: processing of multiplication; processing when the dividend is 0
11. Copy certain files in the specified directory to the specified directory. Requirements:
#1. Receive two parameters from the command line parameters, namely Source directory and target directory
#2. If the source directory does not exist, an error should be reported
#3. If the target directory does not exist, create one
#4. If If the target already exists but is not a directory, an error will be reported
#5. Only copy regular files and soft link files
#6. For regular files, only files less than 1M in size will be copied
# vim /test.sh
#!/bin/bash
function displayHelp()
{
echo "Usage: $(basename $0) SRCDIR DSTDIR"
}
function getSize()
{
file=$1
size=$(ls -l $file | awk '{print $5}')
echo $size
}
if test $# -ne 2; then
displayHelp >&2
exit 1
fi
srcdir=$1
dstdir=$2
if test ! -d "$srcdir"; then
echo "$srcdir not exists or is not a directory" >&2
exit 1
fi
if test ! -e "$dstdir"; then
mkdir "$dstdir"
fi
if test ! -d "$dstdir"; then
echo "$dstdir is not a directory" >&2
exit 1
fi
for file in $srcdir/*
do
if test -L $file; then
cp -a $file $dstdir/
elif test -f $file; then
---------------------------------------------------
size=$(getSize $file)
if test "$size" -lt 1048576; then
cp -a $file $dstdir/
fi
---------------------------------------------------
find $file -type f -size -1024k -exec cp -a {} $dstdir/ \;
---------------------------------------------------
fi
done

The above is the detailed content of What is a shell? Introduction to common types of shells. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template