linux - 脚本不会自动从 root 用户切换到普通用户

标签 linux shell scripting centos

我以 root 身份登录,而不是运行包含以下内容的脚本

#! /bin/bash
id studentapp if [ $? -eq 0 ]; 
then  echo " SKIPPING user creation" 
else useradd studentapp 
echo " User created" 
fi 
cd /home/studentapp

任何想法...

最佳答案

如果创建了用户,也许您需要在 else block 中使用 su Studentappcd 更改工作目录。如果未创建用户 - 可能没有这样的目录。

su man page

cd man page

此外,它对您也有帮助:

check if user exists

check if direcory exists

更新

#! /bin/bash
id studentapp
if [ $? -eq 0 ];
then
    echo "user exists" 
else
    useradd studentapp --create-home
    passwd studentapp
    echo "user created" 
fi
su studentapp
cd /home/studentapp

关于linux - 脚本不会自动从 root 用户切换到普通用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52803970/

相关文章:

bash - 为每次运行的 bash 脚本维护日志

linux - 为 Linux bash 或 shell 脚本提供自动完成和错误检测的 IDE?

regex - 通过 linux shell 执行文本

linux - 某些网站仅在 Linux 上的 Firefox 中返回禁止响应(尽管将用户代理更改为 Chrome 是可行的);常见的原因?

linux - 为什么 [ -n $var ] 在空字符串上为真?

Windows 批处理脚本 : compare two files' created dates

linux - 只有变量的 Bash 函数

java - 在 Linux 中禁用 log4j 控制台日志记录

linux - 需要一些帮助编写 shell 脚本来添加数字

javascript - 使用 javascript 打开 shell