@rob mayoffの答えはこれを達成するための最も簡単な方法ですが、「実際の」プログラミング言語に慣れている人々のためのいくつかの標準的な落とし穴を指摘するために、擬似コードを実際のシェル構文に変換することに挑戦したいと思いました。最初に3つの一般的な注意事項:
- シェルが異なれば機能も異なるため、bash拡張機能が必要な場合は、 bashを使用します(つまり、スクリプトをコマンドで開始する
#!/bin/bash
か、コマンドで実行します)。bash
基本的なBourneシェルの機能と構文のみを使用している場合は、代わりにsh(#!/bin/sh
またはコマンド)を使用して実行してください。sh
わからない場合は、bashが必要だと想定してください。
- 後で実行するためのコマンドを作成するとき、遭遇する可能性のあるあらゆる種類の構文解析の奇妙さがあります(BashFAQ#050:コマンドを変数に入れようとしていますが、複雑なケースは常に失敗します!)。最善の方法は、通常、文字列ではなく配列として作成することです。「もちろん、配列はbashの拡張機能であり、基本的なシェル機能ではありません...
- シェル構文では、スペースが重要です。たとえば、コマンド
if [ -n "$2" ]; then
では、セミコロンの後のスペースはオプションですが(セミコロンの前にスペースがある場合もあります)、他のすべてのスペースは必須です(これらがないと、コマンドはまったく異なることを行います)。また、割り当てでは、等号の周りにスペースを入れることはできません。そうしないと、(再び)まったく異なることが行われます。
それを念頭に置いて、関数についての私の見解は次のとおりです。
addUser() {
# The function keyword is optional and nonstandard, just leave it off. Also,
# shell functions don't declare their arguments, they just parse them later
# as $1, $2, etc
bashCmd=(useradd -m)
# you don't have to declare variable types, just assign to them -- the
# parentheses make this an array. Also, you don't need semicolons at the
# end of a line (only use them if you're putting another command on the
# same line). Also, you don't need quotes around literal strings, because
# everything is a string by default. The only reason you need quotes is to
# prevent/limit unwanted parsing of various shell metacharacters and such.
# Adding the initial user group
if [ -z "$3" ]; then
# [ is actually a command (a synonym for test), so it has some ... parsing
# oddities. The -z operator checks whether a string is empty (zero-length).
# The double-quotes around the string to be tested are required in this case,
# since otherwise if it's zero-length it'll simply vanish. Actually, you
# should almost always have variables in double-quotes to prevent accidental
# extra parsing.
# BTW, since this is a bash script, we could use [[ ]] instead, which has
# somewhat cleaner syntax, but I'm demonstrating the difficult case here.
bashCmd+=(-g users)
else
bashCmd+=(-g "$3")
# Here, double-quotes here are not required, but a good idea in case
# the third argument happens to contain any shell metacharacters --
# double-quotes prevent them from being interpreted here. -g doesn't
# have any shell metacharacters, so putting quotes around it is not
# necessary (but wouldn't be harmful either).
fi
# Adding any additional groups
if [ -n "$4" ]; then
bashCmd+=(-G "$4")
fi
# Set the login shell
if [ -z "$2" ]; then
bashCmd+=(-s /bin/bash "$1")
else
bashCmd+=(-s "$2" "$1")
fi
# Finally, run the command
"${bashCmd[@]}"
# This is the standard idiom for expanding an array, treating each element
# as a shell word.
}