使用Shell判断当前用户是否存在
方式一:使用id命令判断用户是否存在,若存在则返回值为1,不存在则返回值为0
- #!/bin/bash
- id root >/dev/null 2>&1
- if [ $? -eq 1 ]; then
- echo "用户不存在"
- else
- echo "用户已存在"
- exit 1
- fi
方式二:根据/etc/passwd文件中是否有root关键字,判断root用户是否存在
- #!/bin/bash
- if grep -q "root" /etc/passwd; then
- echo "用户已经存在"
- else
- echo "用户不存在"
- fi
方式三:使用whoami命令判断当前用户是否为root
- #!/bin/bash
- if [ `whoami` == "root" ];then
- echo "当前用户为root"
- else
- echo "当前用户不是root,已退出"
- exit 1
- fi