スクリプトにパラメータを渡すときにこの問題が発生しました。ケースメニューに対応する機能が実行されていません。スクリプトはパラメータを入力として受け入れ、適切な操作を実行します。
#!/bin/bash
usage () {
echo " Usage:
-h, --help #Displaying help
-p, --proc #Working with directory /proc
-c, --cpu #Working with CPU
-m, --memory #Working with memory
-d, --disks #Working with disks
-n, --network #Working with networks
-la, --loadaverage #Displaying the load average on the system
-k, --kill #Sending signals to processes
-o, --output #Saving the results of script to disk"
exit2
}
proc () {
if [ -n "$1" ]
then
if [ -z "$2" ]
then
ls /proc
else
cat /proc/"$2"
fi
fi
}
parsed_arguments=$(getopt -o hp:c:m:d:n:la:k:o: --long help,proc:,cpu:,memory:,disks:,network:,loadaverage:,kill:,output:)
if [[ "${#}" -eq "" ]]
then
usage
fi
eval set -- "$parsed_arguments"
while :
do
case "$1" in
-h | --help) echo " Showing usage!"; usage
;;
-p | --proc) proc
;;
esac
done
スクリプトが引数を受け取らない場合は、オプションの説明を表示する必要がありますが、スクリプトが「-」または「--」で始まる最初の引数を入力として受け取ると、次の文字または単語に対応する関数を実行する必要があります。 「-」または「--」。はい
No parameters:
./script.sh
Usage:
-h, --help #Displaying help
-p, --proc #Working with directory /proc
-c, --cpu #Working with CPU
-m, --memory #Working with memory
-d, --disks #Working with disks
-n, --network #Working with networks
-la, --loadaverage #Displaying the load average on the system
-k, --kill #Sending signals to processes
-o, --output #Saving the results of script to disk"
With one parameters:
./script.sh -p
or
./script.sh --proc
The contents of the /proc directory should be displayed
With additional parameters:
]]./script.sh -p cpuinfo
or
./script.sh --proc cpuinfo
The contents of the file passed through the additional parameter should be displayed
パラメータなしでスクリプトを実行しますが、パラメータを含むスクリプトは実行しません。スクリプトにパラメータを渡すときに、その関数が実行されない理由が何であるかを教えてください。
ベストアンサー1
getopt
コマンドラインパラメータは独自のパラメータとして解析する必要があります。実際に機能するutil-linux / Busybox getoptを使用している場合、正しい構文は通常、次--
のように引数を追加して解析することです。
getopt -o abc --long this,that -- "$@"
ここでは"$@"
スクリプト自体のパラメータに展開されます。
while
これにより、パラメータを使用せずshift
に常に同じパラメータを確認するため、無限ループが発生します$1
。
スクリプトに他の問題がある可能性がありますが、これらの問題を解決するには始める必要があります。を使用してスクリプトを実行するか、スクリプトの先頭に追加してbash -x myscript
コマンドを表示できます。set -x
実際に走る。
バラよりgetopt、getopts、または手動解析 - 短いオプションと長いオプションの両方をサポートするには何を使用する必要がありますか?またはこの回答または私の答えはここにあります使用方法の例ですgetopt
。