1. ホーム
  2. スクリプト・コラム
  3. リナックスシェル

シェルスクリプトの基礎と原理入門

2022-01-05 18:43:31

1. 特殊変数

$#: 変数パラメータの数を表示する
0:スクリプトの名前を表示
$! : シェルのバックエンドの pid を表示します。
$@ : 渡されたスクリプトの全パラメータのリストを表示する
$*: すべてのパラメータのリストを表示し、1 つの文字列として表示します。
$$:スクリプトのプロセス自体のID
直前のコマンドの結果。

2. 内部環境変数

$PATH 
SHELL The shell currently in use
UID Current user environment {0|other number}={root|other user}
HOME Current user directory
PWD Current directory	
HISTFILE History command path
PS1 #[\u@\h \W]\$ user@hostname\directory\$

3.文字判定だけでなく、整数判定も可能

3.1 整数判定

-eq Test if two integers are equal (equal)
-ne Tests if two integers are unequal (unequal)
-gt Tests if a number is greater than a number (greater than)
-lt tests if a number is less than a number (less than)
-ge Tests if a number is greater than or equal to 
-le Tests if a number is less than or equal to

3.2 キャラクターテスト

=~ Test if a regular expression matches
-z "string" tests if the character is null, true if null, false if not e.g.: [ -z "" ] is vacuum then true
-n "string" detects if the character is not empty, true if not empty, false if not empty
characters compare size with [[ ]], than the first letter (a-zA-Z) are uppercase or are lowercase compare ascii value the larger the larger
There are upper case and lower case then A>a B>b but A is not greater than the case of b
[root@slave02 ~]# [[ "A" < "B" ]]
[root@slave02 ~]# echo $?
0
[root@slave02 ~]# [[ "a" < "b" ]]
[root@slave02 ~]# echo $?
0

4. ファイル判定

-e: whether the file exists or not   
-b: test for block device files
-c: test for character device files
-f: test for normal files
-d: test for directories
-h: test if symbolic link file
-L: test if it is a symbolic link file
-p: test if it is a named pipe file
-S: test if it is a socket file
Permissions related.
-r read
-w write
-x execute
Special permissions
-g
-u
-k
etc.

5.入力を読む

Options.
-p: specify the prompt character
-t: specify how long to wait for the prompt (in seconds)

6. もしもの時の判断

Multi-branching.
if [ condition ];then
	statement1
.....
elif [ condition2 ];then
statement2
....
else
statement3
....
fi

7. ケース選択判定

case $variable name in            
	'value1')                
		 statement                
		 ...                
 ;;            
	'value2')                
 		statement                
 		...                
 ;;            
*)                
 		statement                
 		...                
 ;;        
esac

Wildcard characters supported by #case.
    * //any length arbitrary character
    ?           //any single character of any length
    [] //any single character in the word range
   start|START //both options

8. フォーループ

First one.
for ((expr1;expr2;expr3)) # expr1: initial value condition  
								# expr2: the range of the loop to exit  
								# expr3: the value of the variable to use
{
loop body
}
for ((expr1;expr2;expr3));do            
Loop body
done
Second type.
for variables in list; do
loop
done

9. while ループ

The while loop is used in scenarios where the number of loops is not known, note that there is an exit condition
while [ condition ];do
	statement
	.....
done

10. インデプスエクササイズ

1. 3つの数の足し算、引き算、掛け算、割り算を行うスクリプトを作成する

[root@slave02 ~]# cat script01.sh 
#! /bina=$1
b=$2
c=$3
num1=$[$a+$b+$c]
num2=$[$a-$b-$c]
num3=$[$a*$b*$c]
echo "$a + $b + $c" = $num1
echo "$a - $b - $c" = $num2
echo "$a * $b * $c" = $num3
awk "BEGIN{printf \"$a/$b/$c=%.2f\n\",$a/$b/$c}"
[root@slave02 ~]# source script01.sh 100 10 9
100 + 10 + 9 = 119
100 - 10 - 9 = 81
100 * 10 * 9 = 9000
100/10/9 = 1.11

2. 数字当てゲーム

ルール 数字を指定し、その数字が推測できれば合格、そうでなければ数字の大小を示す

[root@master ~]# cat test03.sh 
#! /binnums=99
read -p "please enter a number: " num
if [ $num -gt $nums ];then
        echo "The number is bigger"
elif [ $num -lt $nums ];then
        echo "number is small"
else
        echo "Guess right"
fi        
[root@master ~]# . test03.sh 
please enter a number: 10
The number is small
[root@master ~]# . test03.sh
please enter a number: 100
The number is too large
[root@master ~]# . test03.sh
please enter a number: 99
Guess right

3. nginxのサービスを勝手に起動するように設定するスクリプトを書く

#$0 is nginx itself $1 is the variable corresponding to the following start|stop|restart|status
[root@192 init.d]# pwd
/etc/init.d
[root@192 init.d]# cat nginx 
#! /bincase $1 in
        'start')
          /usr/local/nginx/sbin          ;;
        'stop')
          /usr/local/nginx/sbin/nginx -s stop
          ;;
        'restart')
        /usr/local/nginx/sbin/nginx -s stop
        /usr/local/nginx/sbin          ;;
        'status')
          num=$(ps -ef |grep -v 'grep'|grep -c nginx:)
          if [ $num -eq 0 ];then
                 echo "nginx is stopped" 
          else
                 echo "nginx is running"
          fi
          ;;
        *)
              echo "Usage: service $0 start|stop|restart|status"
          ;;          
esac
		# When judging the number of nginx processes, the service is considered to be on, otherwise it is considered to have failed

4. forループを使ってユーザー番号1-100を作成する

# create users user1-100
[root@master ~]# cat test05.sh 
#! /binfor (( i=1;i<=100;i++));do
        useradd user$i
        id user$i &>/dev        if [ $? -eq 0 ];then # As long as the user is judged successful, $? will only show 0, if it shows 0, it means execute the next command, otherwise it shows user and existence
                echo "success"
        else	
        		echo "user is exis"    
        fi
done

5. whileループを使って、1+2...100の値を計算する。

[root@slave02 ~]# cat which.sh 
#! /bins=0 # initial value 0
i=1 # value to judge, eventually stop at 100
while [ $i -le 100 ];do
s=$[$s+$i]			 
i=$[$i+1] #Self-incrementing number
done
echo $s
[root@slave02 ~]# source which.sh 
5050
						# If you enter a random number for calculation, change 100 to $1

6. apache簡易コンパイル・デプロイスクリプト

1. general project or script, file, put in the appropriate location, easy to find
[root@slave02 tmp]# pwd
[root@slave02 tmp]# ls
apache
[root@slave02 apache]# ls
install_apache.sh soft
[root@slave02 soft]# ls
apr-1.7.0.tar.bz2 apr-util-1.6.1.tar.bz2 httpd-2.4.48.tar.bz2 httpd.service
[root@slave02 apache]# cat install_apache.sh #! /bin/bash echo "Welcome to this script" apachedir=/usr/local/apache if [ $UID -ne 0 ];then
        echo "Dude, please run as administrator"
fi
echo "Installing dependency packages... "
yum -y install epel-release bzip2 "@Development Tools" &>/devyum -y install openssl-devel pcre-devel expat-devel libtool gcc gcc-c++ make &>/devid apache &>/devif [ $? -ne 0 ];then
        useradd -r -M -s /sbin/nologin apache
fi
cd /tmp/apache/softtar -xf apr-1.7.0.tar.bz2
tar -xf apr-util-1.6.1.tar.bz2
tar -xf httpd-2.4.48.tar.bz2
sed -i '/ $RM "$cfgfile"/d' apr-1.7.0echo "Compiling and installing apr, please listen to the song and relax ....... " 
cd apr-1.7.0[ ! -d /usr/local/apr ]
if [ $? -eq 0 ];then
        . /configure --prefix=/usr/local/apr && make && make install &>/develse
        echo "apr is installed"
fi
cd ... /apr-util-1.6.1[ ! -d /usr/local/apr-util ]
if [ $? -eq 0 ];then
        . /configure --prefix=/usr/local/apr-util --with-apr=/usr/local/apr && make && make install &/develse
        echo "apr-util is installed"
fi
cd ... /httpd-2.4.48[ ! -d /usr/local/apache/ ]
if [ $? -eq 0 ];then
. /configure --prefix=$apachedir \
        --sysconfdir=/etc/httpd24 \
        --enable-so \
        --enable-ssl \
        --enable-cgi \
        --enable-rewrite \
        --with-zlib \
        --with-pcre \
        --with-apr=/usr/local/apr \
        --with-apr-util=/usr/local/apr-util/ \
        --enable-modules=most \
        --enable-mpms-shared=all \
        --with-mpm=prefork
        make && make install &>/develse
        echo "httpd is installed"
fi
cd
# Add judgment if it has an effect, ignore if it doesn't
echo "export PATH=$apachedir/bin:\$PATH" > /etc/profile.d/httpd.sh
ln -s $apachedir/include/ /usr/include/apache &>/devgrep 'apache/man' /etc/man_db.conf &>/dev
if [ $? -eq 1 ];then
        sed -i "20aMANDATORY_MANPATH $apachedir/man" /etc/ma