2017-04-02 15 views
-1

シェルスクリプトを実行しようとしていますが、問題が発生しています。私は、引数を渡すときにコードの特定のセットを実行したい、残りの引数を渡さないと、実行する必要があります。私は引数で実行したい パート:任意の引数なしLinuxでコマンドライン引数を使用しないでシェルスクリプトを実行する

#!/bin/bash 
while [[ "$1" != "" ]]; do 
case "$1" in 
    -c) cat /proc/cpuinfo | grep cores 
      ;; 
    -d) fdisk -l | grep Disk | awk '{print $1,$2,$3,$4}' #fdisk -l 2> /dev/null | grep Disk | grep -v identifier 
      ;; 
    esac 
shift 
done 

この部分

while [[ $# -eq 0 ]]; do 
echo PART 2 $# 
cat /proc/cpuinfo | grep cores 
fdisk -l | grep Disk | awk '{print $1,$2,$3,$4}' #fdisk -l 2> /dev/null | grep Disk | grep -v identifier 
break 
done 

私は問題がループ状態にあると信じて、しかし、私は何を理解するカント?

答えて

1
if [[ -n "$1" ]]; then 
    # 
    # "$1" is not empty. This is the part which runs when one or more 
    # arguments are supplied. 
    # 
    while [[ -n "$1" ]]; do 
    case "$1" in 
    -c) cat /proc/cpuinfo | grep cores 
     ;; 
    -d) LC_ALL=C fdisk -l | grep Disk | awk '{print $1,$2,$3,$4}' 
     #LC_ALL=C fdisk -l 2> /dev/null | grep Disk | grep -v identifier 
     ;; 
    esac 
    shift 
    done 
    exit 
fi 
# 
# "$1" is empty. The following code runs when no arguments are supplied. 
# 
echo PART 2 $# 
cat /proc/cpuinfo | grep cores 
LC_ALL=C fdisk -l | grep Disk | awk '{print $1,$2,$3,$4}' 
#LC_ALL=C fdisk -l 2> /dev/null | grep Disk | grep -v identifier 

注1:テストされていません。

注2:特定の単語やフレーズを検索するコマンドの出力を解析する必要があると感じる場合は、デフォルトのロケールでコマンドを接頭辞LC_ALL=Cで実行することをお勧めします。このようにフランス語のロケールでは、fdiskDisqueと表示されます...

+0

このように、私のロジックが失敗した理由を説明してください。 – Ismail

+0

投稿されたコードが完全なスクリプトであると仮定すると、最初の部分 '$#'の後は、最初からゼロだったか、 'shift'edすべての引数があるので、明らかに常に0になるので、2番目の部分は無条件に実行されます。 – AlexP

+0

説明していただきありがとうございます。 – Ismail

関連する問題