Linux declare コマンド
Linux declare コマンドは、シェル変数を宣言するために使用します。
declare はシェルのコマンドであり、最初の構文では変数を宣言し、変数の属性を設定するために使用できます([rix] が変数の属性です)。2番目の構文では、シェル関数を表示するために使用できます。引数を何も指定しない場合、すべてのシェル変数と関数が表示されます(set コマンドを実行した場合と同じ効果です)。
構文
declare [+/-][rxi][变量名称=设置值] 或 declare -f
引数の説明:
- +/- 「-」は変数の属性を指定するために使用でき、「+」は変数に設定された属性を取り消します。
- -f 関数のみを表示します。
- r 変数を読み取り専用に設定します。
- x 指定した変数は環境変数になり、シェル以外のプログラムでも使用できます。
- i [設定値]には、数値、文字列、または演算式を指定できます。
例
整数型変数を宣言
例
# declare -i ab //整数型変数を宣言
# ab=56 //変数の内容を変更
# echo $ab //変数の内容を表示
56
# ab=56 //変数の内容を変更
# echo $ab //変数の内容を表示
56
変数の属性を変更
例
# declare -i ef //整数型変数を宣言
# ef=1 //変数への代入(整数値)
# echo $ef //変数の内容を表示
1
# ef="wer" //変数への代入(テキスト値)
# echo $ef
0
# declare +i ef //変数の属性を取り消す
# ef="wer"
# echo $ef
wer
# ef=1 //変数への代入(整数値)
# echo $ef //変数の内容を表示
1
# ef="wer" //変数への代入(テキスト値)
# echo $ef
0
# declare +i ef //変数の属性を取り消す
# ef="wer"
# echo $ef
wer
変数を読み取り専用に設定
例
# declare -r ab //変数を読み取り専用に設定
# ab=88 //変数の内容を変更
-bash: ab: 読み取り専用変数
# echo $ab //変数の内容を表示
56
# ab=88 //変数の内容を変更
-bash: ab: 読み取り専用変数
# echo $ab //変数の内容を表示
56
配列変数を宣言
例
# declare -a cd='(
# echo ${cd[1]}
b //変数の内容を表示
# echo ${cd[@]} //配列変数の全体の内容を表示
a b c
# echo ${cd[1]}
b //変数の内容を表示
# echo ${cd[@]} //配列変数の全体の内容を表示
a b c
関数を表示
例
# declare -f
command_not_found_handle ()
{
if [ -x /usr/lib/command-not-found ]; then
/usr/bin/python /usr/lib/command-not-found -- $1;
return $?;
else
if [ -x /usr/share/command-not-found ]; then
/usr/bin/python /usr/share/command-not-found -- $1;
return $?;
else
return 127;
fi;
fi
}
command_not_found_handle ()
{
if [ -x /usr/lib/command-not-found ]; then
/usr/bin/python /usr/lib/command-not-found -- $1;
return $?;
else
if [ -x /usr/share/command-not-found ]; then
/usr/bin/python /usr/share/command-not-found -- $1;
return $?;
else
return 127;
fi;
fi
}
Linux コマンド大全