Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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

like image 658
ctrl-alt-delor Avatar asked Jan 20 '14 12:01

ctrl-alt-delor


People also ask

How do I create a prompt in bash?

You can use the built-in read command ; Use the -p option to prompt the user with a question. It should be noted that FILEPATH is the variable name you have chosen, and is set with the answer to the command prompt.

Which command is used for making the scripts interactive?

Which command is used for making the scripts interactive? 8. read command is shell's internal tool. Explanation: read command is the shell's internal tool for taking input from the user i.e. it makes the scripts interactive.


1 Answers

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.

like image 58
Igor Chubin Avatar answered Sep 21 '22 08:09

Igor Chubin