You can try simply,
Create file named myscript
with following content:
#!/bin/bash
echo -n "Enter Run level":
read rl;
sudo init $rl;
Where echo
is used to print what to input, read
is used to get the input and store into variable rl
and sudo init $rl;
to execute command for changing run level.
For more control/verification over input, you can use loop such as while
and case
.
You've to give execution permission:sudo chmod +x myscript
so that it can be executed.
Then you can run script like:
$ ./myscript
$ Enter Run level : 3
EDIT:
as @RuiFRibeiro suggested, the command to change runlevel is telinit
:
NAME
telinit - change system runlevel
SYNOPSIS
telinit [OPTION]... RUNLEVEL
DESCRIPTION
telinit may be used to change the system runlevel.
So, You should use telinit
instead init
in script.
And to check run level you can use who -r
or runlevel
command which output previous and current runlevel.
$ who -r | awk '{print $1,$2}'
run-level 3
$ runlevel
2 3
telinit
is a backwards compatibility command that "should not be used anymore". – JdeBP Dec 21 '15 at 14:10