第二十四課LinuxShellプログラミング二の使用構造化命令

14561 ワード

説明:本の一部の内容はすべて書籍「Linuxコマンドラインとshellスクリプトプログラミング大全書」から取って、著作権は元の作者の所有になります.***
第十二章:構造化命令本章の内容を使用する
  if-then  
  if  
test  
      
          
case  
12.1 if-then文フォーマットを使用する:
if command
then
command
fi
または
if command; then
command
fi
ステートメント説明:bash shellのif文は、ifの後のそのコマンドを実行します.このコマンドの終了状態コードが0であれば、thenの部分にあるコマンドは実行されます.0でない場合は、then部分のコマンドを実行せずに、スクリプト内の次のコマンドを実行し続けます.fi文はif-then文を表します.これで終わります.
test 1.shスクリプトを作成する
#!/bin/bash
# testing the if statement
if pwd
then
    echo It worked
fi
test 2.shスクリプトを作成する
#!/bin/bash
# testing a bad command
if IamNotaCommand
then 
    echo "It worked"
fi
echo "We are outside the if statement"
test 3.shスクリプトを作成する
#!/bin/bash
if grep $testuser /etc/passwd
then 
    echo "This is my first command"
    echo "This is my second command" 
    echo "I can even put in other commands besides echo:"
    ls -a /home/$testuser/.b*
fi
12.2 if-then-else文フォーマット
if command
then 
command
else
command
fi
ステートメント説明:if文のコマンドが終了状態コード0に戻ると、then部分のコマンドが実行されます.ステータスコードが0でない場合、else部分のコマンドが実行されます.
test 4 shスクリプトを作成する
#!/bin/bash
# testing multiple commands in the then section

testuser=nosuchuser

if grep $testuser /etc/passwd
then 
    echo "This is my first command"
    echo "This is my second command" 
    echo "I can even put in other commands besides echo:"
    ls -a /home/$testuser/.b*
else
    echo "The user $testuser does not exist on this system."
fi
12.3ネストifは、/etc/passwdファイルにあるユーザとそのユーザのディレクトリがまだあるかどうかを確認し、ネストされたif-then文を使用することができます.ネストされたif-then文は、主if-then-else文のelseコードブロックにあります.
ステートメントの書式
if command1
then
commands
elif command2
then
more commands
else
moreandmore commands
fi
ステートメント説明:まずcommand 1を実行し、状態コードが0に戻るとcommandを実行し、elifからfiまでのコマンドはスキップします.commmand 1が状態コードに戻り0でない場合、command 2、command 2の戻り状態コードが0である場合、more commandが実行される.0でない場合は、moredmore commundsを実行します.
test 5 shスクリプトを作成する
#!/bin/bash
# testing nested ifs - use elif

testuser=nosuchuser

if grep $testuser /etc/passwd
then
    echo "The user $testuser exists on this system."
elif ls -d /home/$testuser
then
    echo "The user $testuser dose not exist on this system."
    echo "However,$testuser has a directory"
else
    echo "The user $testuser dose not exist on this system."
    echo "And,$testuser dose not have a directory"
fi
コツ:elif文では、その後のelse文はelifコードブロックに属します.これらは以前のif-thenコードブロックに属していません.
複数のelif文を連結することができます.
if command1
then
command set 1
elif command2
then
command set 2
elif command3
then
command set 3
elif command4
then
command set 5
fi
12.4 testコマンドフォーマット:test conditionコマンド説明:testコマンドにリストされている条件が成立すれば、testコマンドは0に戻ります.さもなければ、非ゼロの状態コードを返します.これでif-then文と結合して使用できます.
ステートメントの書式
if test condition
then
commands
fi
ステートメント説明:testコマンドのcondition部分が空の場合、非ゼロの終了状態コードを返します.
ステートメントの書式
if [ condition ]
then
commands
fi
ステートメント説明:bashellが提供するもう一つのテスト方法は、最初の四角括弧の後と二番目の方括弧の前にスペースを入れなければなりません.
test命令は三つの条件を判断できます.
数値比較文字列比較ファイル比較12.4.1数値比較testコマンドの数値比較機能
n1 -eq n2:  n1    n2
n1 -gen2:  n1       n2
n1 -gt n2:  n1    n2
n1 -le n2:  n1       n2
n1 -lt n2:  n1    n2
n1 -ne n2:  n1     n2
numbericを編纂するtest.shスクリプト
#!/bin/bash
value1=10
value2=11
#
if [ $value1 -gt 5 ]
then
    echo "The test value $value1 is greater then 5"
fi
#
if [ $value1 -eq $value2 ]
then
    echo "The values are equal"
else
    echo "The values are different"
fi
bashellは整数しか処理できません.echoだけで浮動小数点を表示すれば大丈夫です.数値の比較に使うとエラーが発生します.
float at ingを編纂するpoint_test.shスクリプト
#!/bin/bash
#
value1=5.555
#
echo "The test value is $value1"
#
if [ $value1 -gt 5 ]
then
    echo "The test value $value1 is greater then 5"
fi
12.4.2文字列比較文字列比較テスト
str1 = str2:  str1   str2  
str1 != str2:  str1   str2  
str1 < str2:  str1   str2 (           )
str1 > str2:  str1   str2 (           )
-n str2:  str1      0
-z str2:  str1      0
1.文字列の等しい性
test 7.shスクリプトを作成する
#!/bin/bash
# testing string equality
testuser=rich
#
if [ $USER = $testuser ]
then
    echo "Welcome $testuser"
else
    echo "This is not $testuser"
fi
test 8.shスクリプトを作成する
#!/bin/bash
# testing string equality
testuser=rich
#
if [ $USER != $testuser ]
then
    echo "This is not $testuser" 
else
    echo "Welcome $testuser"  
fi
2.文字列の順序
test 9.shスクリプトを作成する
#!/bin/bash
# mis-using string comparisons
#
val1=baseball
val2=hockey
#
if [ $val1 \> $val2 ]
then
    echo "$val1 is greater than $val2" 
else
    echo "$val1 is less than $val2"
fi
注意:文字列の比較では標準のASCII順を使い、各文字のASCII値に基づいてソート結果を決定します.大文字は小文字より小さいと考えられます.しかし、ソト命令は正反対です.
説明:testコマンドとテスト表式は、標準的な数学的比較記号を用いて文字列比較を表し、テキストコード(例えば、-eq、-geなど)で数値比較を表します.この細かい特性は多くのプログラマーに理解されて逆になった.データ演算子を数値に使うと、shellは文字列の値として扱われ、正しい結果が得られない可能性があります.
3.文字列のサイズ
test 10.shスクリプトを作成する
#!/bin/bash
# testing string length
val1=testing
val2=''
#
if [ -n $val1 ]
then
    echo "The string '$val1' is not empty" 
else
    echo "The string '$val1' is empty"
fi
#
if [ -z $val2 ] 
then
    echo "The string '$val2' is empty"
else
    echo "The string '$val2' is not empty"
fi
#
if [ -z $val3 ] 
then
    echo "The string '$val3' is empty"
else
    echo "The string '$val3' is not empty"
fi
ノック:空いている変数と初期化されていない変数は、shellスクリプトテストに災難的な影響を与えます.変数の内容があまり確定されていない場合は、数値または文字列の比較に使う前に、まず-nまたは-zを通して変数に値が含まれているかどうかをテストしたほうがいいです.
12.4.3ファイル比較testコマンドのファイル比較機能
-d file:  file          
-e file:  file    
-f file:  file          
-r file:  file       
-s file:  file       
-w file:  file       
-x file:  file        
-O file:  file            
-G file:  file                
file1 -nt file2:  file1   file2 
file1 -ot file2:  file1   file2 
1.チェックリスト
-dテストは、指定されたディレクトリがシステムに存在するかどうかを確認します.ファイルを目次に書き込むつもりなら、あるいはディレクトリに切り替えるつもりなら、先進行のテストはいつもいいことです.
test 11.shスクリプトを作成する
#!/bin/bash
# Look before you leap
#
jump_directory=/home/zc
#
if [ -d $jump_directory ]
then
    echo "The $jump_directory directory exists"
    cd $jump_directory
    ls
else
    echo "The $jump_directory directory dose not exist"
fi
2.オブジェクトの存在を確認する
-e比較により、ファイルまたはディレクトリを使用する前に、スクリプトコードが存在するかどうかを確認します.
test 12.shスクリプトを作成します.
#!/bin/bash
# Check if either a directory or file exists
#
location=$HOME
file_name="sentinel"
#
if [ -e $location ]
then #Directory does exist
    echo "OK on the $location directory."
    echo "Now checking on the file, $file_name."
    #
    if [ -e $location/$file_name ]
    then #File does exist
        echo "OK on the filename"
        echo "Updating Current Date..."
        date >> $location/$file_name
    #
    else #File does not exist
        echo "File does not exist"
        echo "Nothing to update"
    fi
#
else #Directory does not exist
    echo "The $location directory does not exist."
    echo "Nothing to update"
fi
3.ファイルをチェックする
-e比較はファイルとディレクトリに使用できます.指定されたオブジェクトをファイルとして決定するには、-fで比較する必要があります.
編纂test 12 sh
#!/bin/bash
# check if either a directory or file exists
#
item_name=$HOME
echo
echo "The item being checked: $item_name"
echo
#
if [ -e $item_name ]
then #Item does exist
    echo "The item, $item_name, does exist."
    echo "But is it a file?"
    echo
    #
    if [ -f $item_name ]
    then #Item is a file
        echo "Yes, $item_name is a file."
    #
    else #Item is not a file
        echo "No, $item_name is not a file."
    fi
#
else #Item does not exist
    echo "The item, $item_name, does not exist."
    echo "Nothing to update"
fi
4.読み取り可能かどうかを確認する
ファイルからデータを読み取る前に、ファイルが読めますか?
test 14.shスクリプトを作成する
#!/bin/bash
# testing if you can read a file
pwfile=/etc/shadow
#
# first, test if the file exists, and is a file
if [ -f $pwfile ]
then
    # now test if you can read it
    if [ -r $pwfile ]
    then
        tail $pwfile
    else
        echo "Sorry, I am unable to read the $pwfile file"
    fi
else
    echo "Sorry, the file $pwfile does not exist"
fi
5.空のファイルをチェックする
s比較を使用してファイルが空かどうかを確認します.-s比較が成功した場合、ファイルにデータがあると説明します.
test 15.shスクリプトを作成する
#!/bin/bash
# Testing if a file is empty
#
file_name=$HOME/sentinel
#
if [ -f $file_name ]
then
    if [-s $file_name ]
    then
        echo "The $file_name file exists and has data in it."
        echo "Will not remove this file."
    else
        echo "The $file_name file exists,but is empty."
        echo "Deleting empty file..."
        rm $file_name
    fi
else
    echo "File,$file_name,does not exist."
fi
6.書くかどうかチェックする
使用-w比較でファイルに書き込む権限があるかどうかを判断します.
test 16.shスクリプトを作成する
#!/bin/bash
# check if a file is writable.
#
item_name=$HOME/sentinel
echo
echo "The item being checked: $item_name"
echo
#
if [ -e $item_name ]
then #Item does exist
    echo "The item, $item_name, does exist."
    echo "But is it a file?"
    echo
    #
    if [ -f $item_name ]
    then #Item is a file
        echo "Yes, $item_name is a file."
        echo "But is it writable?"
        echo
        #
        if [ -w $item_name ]
        then #Item is writable
            echo "Writing current time to $item_name"
            date +$H$M >> $item_name
        #
        else #Item is not writable
            echo "Unable to write to $item_name"
        fi
    #
    else #Item is not a file
        echo "No, $item_name is not a file."
    fi
#
else #Item does not exist
    echo "The item, $item_name, does not exist."
    echo "Nothing to update"
fi
7.ファイルの実行可能性を確認する
使用-x比較は、特定のファイルに実行権限があるかどうかを判断する.
test 17 shスクリプトを作成する
#!/bin/bash
# testing file execution
#
if [ -x test16.sh ]
then 
    echo "You can run the script:"
    ./test16.sh
else
    echo "Sorry, you are unable to execute the script"
fi
8.所属関係をチェックする
使用-O比較テスト現在のユーザはファイルの所有者ですか?
test 18 shスクリプトを作成する
#!/bin/bash
# eheck file ownership
#
if [ -O /etc/passwd ]
then 
    echo "You are the owner of the /etc/passwd file"
else
    echo "Sorry, you are not the owner of the /etc/passwd file"
fi
9.デフォルトのグループ関係をチェックする
G比較チェックファイルのデフォルトグループを使用して、ユーザーのデフォルトグループにマッチしたらテストに成功します.注:-G比較は、ユーザが所属しているグループではなく、標準グループのみを確認します.
test 19.shスクリプトを作成する
#!/bin/bash
# check file group test
#
if [ -G $HOME/testing ]
then
    echo "You are in the same group as the file"
else
    echo  "The file is not owned by you group"
fi
10.ファイルの日付を確認する
を使用して、他のファイルよりファイルが新しいかどうかを判断します.ファイルが新しいなら、作成日が近いです.を使用して、他のファイルよりファイルが古いかどうかを判断します.ファイルが古いなら、ファイルの作成日がもっと早いです.
test 20 shスクリプトを作成する
#!/bin/bash
# testing file dates 
#
if [ test19.sh -nt test18.sh ]
then
    echo "The test19 file is newer than test18"
else
    echo "The test18 file is newer than test19"
fi
if [ test17.sh -ot test19.sh ]
then
    echo "The test17 file is older than the test19 file"
fi
test 21.5 shスクリプトを作成する
#!/bin/bash
# testing file dates 
#
if [ badfile1 -nt badfile2 ]
then
    echo "The badfile1 file is newer than badfile2"
else
    echo "The badfile2 file is newer than badfile1"
fi
これらのコマンドはファイルが存在するかどうかを確認していません.これらのコマンドを使う前に、ファイルが存在することを確認しておかなければなりません.
12.5複合条件テストif-then文は、ブール論理を使用してテストを組み合わせることができます.フォーマットは以下の通りです.
[ condition1 ] && [ condition2 ]
[ condition1 ] || [ condition2 ]
要点:ブール論理は、可能な戻り値をTRUEまたはFALSEに簡略化できる方法である.
test 22.shスクリプトを作成する
#!/bin/bash
# testing compound comparisons
#
if [ -d $HOME ] && [ -w $HOME/testing ]
then
    echo "The file exists and you can write to it"
else
    echo "I connot write to the file"
fi
12.6 if-thenの高級特性12.6.1は、二重括弧コマンドフォーマット:(expression)コマンド説明を使用します.
val++:   
val--:   
++val:   
--val:   
!:    
~:   
**:   
<>:   
&:    
|:    
&&:   
||:   
test 23.shスクリプトを作成する
#!/bin/bash
# using double parenthesis
#
var1=10
#
if (( $val1 ** 2 > 90 ))
then
    (( val2 = $val1 ** 2 ))  
    echo "The square of $val1 is $val2"
fi
12.6.2両方の括弧コマンド形式:[[expression]コマンド説明:一方の括弧に加えて、モードマッチングコマンドの注意を追加しました.すべてのshellが両方の括弧を使ってtest 24 shスクリプトを作成することをサポートしているわけではありません.
#!/bin/bash
# using pattern matching
#
if [[ $USER == z* ]]
then
    echo "Hello $USER"
else
    echo "Sorry,I do not know you"
fi
12.7 case  
  test25.sh  

#!/bin/bash
# looking for a possible value
#
if [ $USER = "zc" ]
then
    echo "Welcome $USER"
    echo "Please enjoy your visit"
elif [ $USER = "barbara" ]
then
    echo "Welcome $USER"
    echo "Please enjoy your visit"
elif [ $USER = "testing" ]
then
    echo "Special testing account"
elif [ $USER = "jessica" ]
then
    echo "Do not forget to logout when you're done"
else
    echo "Sorry, you are not allowd here"
fi
コマンド形式:
      case variable in
      pattern1 | pattern2) commands1;;
      pattern3) commands2;;
      *) commands3;;
      esac
コマンド説明:caseコマンドは、指定された変数を異なるモードと比較します.
test 26.shスクリプトを作成する
#!/bin/bash
# using the case command
#
case $USER in
rich | barbara)
echo "Welcome, $USER"
echo "Please enjoy your visit";;
testing)
echo "Special testing account";;
jessica)
echo "Do not forget to log off when you're done";;
*)
echo "Sorry, you are not allowed here";;
esac
12.8小結構造化命令は、shellスクリプトの正常な実行フローを変更することができる.基本的な構造化命令はif-then文です.ステートメントは、一つのコマンドを実行した結果に基づいて、他のコマンドを実行することができます.この章では、if-then、if-then-else、elif、case文を紹介します.