使 bash 脚本切换到交互模式并给出提示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21234025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:18:10  来源:igfitidea点击:

Making a bash script switch to interactive mode and give a prompt

bash

提问by ctrl-alt-delor

I am writing a training tool, it is written in bash to teach bash/unix.

我正在编写一个培训工具,它是用 bash 编写的,用于教授 bash/unix。

I want a script to run to set things up, then to hand control to the user. I want it to be easily runnable by typing ./script-name

我想要一个脚本来运行设置,然后将控制权交给用户。我希望它可以通过键入轻松运行./script-name

How do I do this?

我该怎么做呢?

I.E.

IE

  • User types: tutorial/run
  • The run-tutorial script sets things up.
  • The user is presented with a task. (this bit works)
  • The command prompt is returned, with the shell still configured.
  • 用户类型: tutorial/run
  • 运行教程脚本进行设置。
  • 向用户呈现一个任务。(这个位有效)
  • 返回命令提示符,仍然配置 shell。

Currently it will work if I type . tutorial/bashrc

目前,如果我输入它会起作用 . tutorial/bashrc

回答by Igor Chubin

There are several options:

有几种选择:

  • You start script in the same shell, using sourceor .;
  • You start a new shell but with your script as a initialization script:
  • 你在同一个 shell 中启动脚本,使用source.;
  • 您启动一个新的 shell,但将您的脚本作为初始化脚本:

The first is obvious; I write a little bit more details about the second.

第一个很明显;我写了关于第二个的更多细节。

For that, you use --init-fileoption:

为此,您使用--init-file选项:

bash --init-file my-init-script

You can even use this option in the shebang line:

您甚至可以在 shebang 行中使用此选项:

#!/bin/bash --init-file

And then you start you script as always:

然后像往常一样启动脚本:

./script-name

Example:

例子:

$ cat ./script-name
#!/bin/bash --init-file
echo Setting session up
PS1='.$ '
A=10
$ ./script-name
Setting session up
.$ echo $A
10
.$ exit
$ echo $A

$

As you can see, the script has made the environment for the user and then has given him the prompt.

如您所见,脚本为用户创建了环境,然后给了他提示。

回答by Gabriel Staples

Try making it an alias in your ~/.bashrc file. Add this to the bottom of ~/.bashrc:

尝试在您的 ~/.bashrc 文件中将其设为别名。将此添加到 ~/.bashrc 的底部:

alias tutorial='. tutorial/bashrc'

Then close and re-open your terminal, or type . ~/.bashrcto re-source it.

然后关闭并重新打开您的终端,或键入. ~/.bashrc以重新获取它。

To use this alias, simply call tutorial, and that will automatically get replaced with its alias, as though you had called . tutorial/bashrc.

要使用此别名,只需调用tutorial,它将自动替换为其别名,就像您调用了. tutorial/bashrc.