@rob mayoff 的回答是完成此任务的最简单方法,但我想我会尝试将您的伪代码转换为真正的 shell 语法,以指出一些习惯于“真正”编程语言的人的标准陷阱。先说三点一般注意事项:
- 不同的shell 有不同的功能,所以如果您需要任何bash 扩展,请使用bash(即使用命令启动脚本
#!/bin/bash
或运行它)。bash
如果您只使用基本的 Bourne shell 功能和语法,请改用 sh (#!/bin/sh
或sh
命令)运行它。如果你不知道,假设你需要 bash。
- 在为以后执行构建命令时,您可能会遇到各种解析异常(请参阅BashFAQ#050:我正在尝试将命令放入变量中,但复杂的情况总是失败!)。最好的方法通常是将其构建为数组,而不是字符串。'当然,数组是 bash 扩展,而不是基本的 shell 功能......
- 在 shell 语法中,空格很重要。例如,在 command
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.
}