Making a bash script switch to interactive mode and give a prompt
Asked Answered
S

2

17

I am writing a training tool, it is written in bash to teach 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

How do I do this?

I.E.

  • 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.

Currently it will work if I type . tutorial/bashrc

Social answered 20/1, 2014 at 12:23 Comment(1)
Some example workflow would really help here.Waverley
D
18

There are several options:

  • You start script in the same shell, using source or .;
  • You start a new shell but with your script as a initialization script:

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

For that, you use --init-file option:

bash --init-file my-init-script

You can even use this option in the shebang line:

#!/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.

Deraign answered 20/1, 2014 at 12:32 Comment(2)
--init-file with nothing following it works. ThanksSocial
Is it possible to detect which script is running when using this trick? On my Mac running with just --init-file causes $0 to expand to "/bin/bash"Unmask
B
0

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

alias tutorial='. tutorial/bashrc'

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

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

Beef answered 19/2, 2020 at 22:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.