9

useradd コマンドの関数をシンプルにして、貧弱なシェル プログラミング スキルをすばやく向上させようとしています。

useradd -m -g [initial_group] -G [additional_groups] -s [login_shell] [username]

現在、オプションの引数を使用して機能する方法が少しわかりません。いくつかのグーグルの後、コードをいじる必要があるだけです。

私が確信していないことの 1 つは論理であり、皆さんがこれをどのように書いているのか興味があります。私が一緒にハッキングできるものよりも優れていると確信しています。


ログインシェルと初期グループのために、関数の引数をセットアップしようとする方法は次のとおりです。

arg1 - userName, required
arg2 - loginShell, optional (default: /bin/bash)
arg3 - initGroup, optional (default: users)
arg4 - otherGroups, optional (default: none)

これは、私がこれをどのように構築しようと考えているかについての不完全な疑似コードです。

function addUser( userName, loginShell, initGroup, otherGroups){
// Not how I would go about this but you should get the point
  string bashCmd = "useradd -m -g ";

// Adding the initial user group
  if(initGroup == null){
    bashCmd += "users";
  } else {
    bashCmd += initGrop;
  }

// Adding any additional groups
  if(otherGropus != null){
    bashCmd += " -G " + otherGroups;
  }

  if(loginShell == null){
    bashCmd += " -s /bin/bash " + userName;
  } else {
    bashCmd += " -s " + loginShell + " " + userName;
  }
}

これらは私が行くリンクです

http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-8.html

パラメータを Bash 関数に渡す

オプションの入力引数を取る bash スクリプトを作成するには?

ヒアドキュメント内での関数の使用

4

3 に答える 3

14

${parameter:+word}展開が役立つ場合があります。Bashリファレンスマニュアルから:

パラメータが null または未設定の場合、何も置換されません。それ以外の場合は、単語の展開置換されます。

そう:

function addUser {
    useradd -m ${2:+-s "$2"} ${3:+-g "$3"} ${4:+-G "$4"} "$1"
}

この関数は、引数のいずれかに変な文字 (スペース、ドル記号、その他のシェル メタ文字など) が含まれている場合、引用符を適切に処理することに注意してください。コマンド文字列をつなぎ合わせようとすると、断片を適切に引用するのがはるかに難しくなります。これがあなたの個人的な短期間の使用のみであり、入力が安全であることがわかっている場合、それは問題ではないかもしれません. ただし、root として実行することを意図しており、その入力を慎重に処理しない場合は、スクリプトまたは関数を放置しないことをお勧めします。

于 2012-11-03T05:52:24.673 に答える
10

@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.
}
于 2012-11-03T17:24:48.007 に答える
0

多くの複雑なサンプルを取得するためのABSの google

function addUser{
userName=$1;
loginShell=$2;
initGroup=$3
otherGroups=$4;

  args=(-m -g);

// Adding the initial user group
  if [[ $initGroup == '' ];then
    args+=(users);
  else 
    args+=("$initGrop");
  fi;

# Adding any additional groups
  if [[ $otherGroups != '' ]];then
    args+=(-G "$otherGroups");
  fi;

  if [[ $loginShell == '' ]];then
    args+=(-s /bin/bash "$userName");
  else
    args+=(-s "$loginShell" "$userName");
  fi;
  useradd "${args[@]}"
}

コードはチェックされていませんが、何も見逃さないことを願っています

于 2012-11-03T05:50:03.767 に答える