首页 > 解决方案 > 如何从 STDIN 获取字符串输入并将其保存在 bash 中的变量中以在脚本的其他部分使用它

问题描述

我正在尝试编写一个脚本,它将在 linux (ubuntu) 服务器上创建一个新用户。我是脚本编写新手,我遇到了问题

如何从用户输入中读取变量并在脚本的其他部分使用该变量

这就是我所拥有的,但在执行过程中陷入困境。谢谢。

update_pkgs() {
  echo "
----------------------
  Prerequisites : Making sure everything is up to date
----------------------
"
  # checks is all pkgs are up to date
  sudo apt-get update -y

  # installing necessary pkgs
  sudo apt-get install build-essential libssl-dev -y
}

create_user() {
  echo "
----------------------
  1. Creating a new user with name `<user>` and gives correct access.
----------------------
"
 # [ASK]: How to make <user> a variable I read from STDIN
 #        and  pass it around in the following commands

  # add new user with the name of `user`
  sudo adduser --ingroup www-data --disabled-password <user>


  # copy ssh/ folder from `ubuntu` user to new user 
  # and gives the right permissions/privileges 
  sudo cp -R .ssh/ /home/<user>/
  sudo chown -R <user>:www-data /home/<user>/.ssh/  
}


# 1. asks to run the script

echo "
----------------------
  Do You Wish to run this Script ?
----------------------
"

select yn in "Yes" "No" create quit; do
    case $yn in
        Yes) 
          update_pkgs();
          create_user(); 
          break;;
        No) exit;;
        create)
        read -p "Enter name of user: " user
        create_user($user)
        quit)
          break;;
        *) 
          echo 'Invalid option $REPLY'
    esac
done

标签: bashshell

解决方案


bash总是按顺序运行命令,除非你告诉它在后台运行命令。

您可以在此处查看如何将标准输入保存到变量中。


推荐阅读