如何从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

解决方法

bash始终按顺序运行命令,除非您告诉它在后台运行命令。

您可以看到如何将标准输入保存到变量here

,

您应该使问题更加集中。至于标题中的请求(如何从STDIN获取输入并将其保存在bash中的变量中),它也太通用了。

答案取决于您希望从stdin(一个单词?一行?几行?)中得到什么,您打算如何处理它(以“标量”变量或数组形式读取?)以及其他因素。

例如,在终端中执行以下命令足以将行从stdin读取到名为var的变量:

read var

但是您肯定想要更多。