som*_*ing 3 command-line shell bash shell-script command
我正在编写一个脚本来配置新的 debian 安装,同时找到确认脚本中存在用户的最佳解决方案,我发现的最佳方法给了我奇怪的输出。
问题:
id -u $var
并id -u $varsome
给出相同的输出,即使
var
有一个值(用户名)并且varsome
没有值
[19:49:24][username] ~ ~??$?? var=`whoami`
[19:53:38][username] ~ ~??$?? id -u $var
1000
[19:53:42][username] ~ ~??$?? echo $?
0
[19:53:49][username] ~ ~??$?? id -u $varsome
1000
[19:09:56][username] ~ ~??$?? echo $?
0
[20:10:18][username] ~ ~??$?? bash --version
GNU bash, version 4.4.12(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
Licens GPLv3+: GNU GPL version 3 eller senere <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
[20:27:08][username] ~ ~??$?? cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 9 (stretch)"
NAME="Debian GNU/Linux"
VERSION_ID="9"
VERSION="9 (stretch)"
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"
Run Code Online (Sandbox Code Playgroud)
我从 stackoverflow 上的这个问题得到了命令:检查用户是否存在
问题:
由于变量扩展没有被引用,因此$varsome
扩展导致的空词被完全删除。
让我们创建一个函数来打印它获得的参数数量并比较引用和非引用的情况:
$ args() { echo "got $# arguments"; }
$ var=""
$ args $var
got 0 arguments
$ args "$var"
got 1 arguments
Run Code Online (Sandbox Code Playgroud)
在您的情况下也会发生同样的情况id
:id -u $var
与id -u
何时var
为空完全相同。由于id
没有看到用户名,它默认打印当前用户的信息。
如果你引用"$var"
,结果是不同的:
$ var=""
$ id -u "$var"
id: ‘’: no such user
Run Code Online (Sandbox Code Playgroud)
修复后,您可以使用它id
来查找用户是否存在。(虽然我们不需要这里的输出,所以将它们重定向。)
check_user() {
if id -u "$1" >/dev/null 2>&1; then
echo "user '$1' exists"
else
echo "user '$1' does not exist"
fi
}
check_user root
check_user asdfghjkl
Run Code Online (Sandbox Code Playgroud)
那将打印user 'root' exists
和user 'asdfghjkl' does not exist
。
这与未引用变量的意外分词引起的常见问题有点相反。但基本问题是相同的,并且由这里一半的答案所解决:总是引用变量扩展(除非你知道你想要未引用的行为)。
看: