5

Is it possible to enter keyboard shortcuts into a bash script? For example, I have tried typing in ^d to substitute for control + d (logout) without success.

ubuntu@vfleet:~$ ^d
-bash: :s^d: substitution failed
ubuntu@vfleet:~$ ^D
-bash: :s^D: substitution failed

I am using screen to run a django development server in the background. One of the commands to run a particular screen as a daemon is control + a + d. The goal is to be able to enter in control + a + d into a bash script. For example:

python manage.py runserver
^a + d

Is this possible?

Edit: A valid method of avoiding the keyboard shortcut in screen is linked by Eric Renouf in the comments below. screen -d -m sh -c "python manage.py runserver" will start a development server as a daemon. This is a great solution for my particular problem, but it would still be nice to have a solution for the original question at hand.

2
  • 2
    If you're just trying to launch something inside a screen session you can do it without ever attaching in the first place. For example stackoverflow.com/questions/2007351/… Commented Jun 30, 2017 at 12:16
  • Your requirement is: You need to start the django dev server everytime the server/machine restarts. If this is your requirement I do have an answer for you. Commented Jun 30, 2017 at 12:23

2 Answers 2

6

xdotool package is the solution here.

xdotool key ctrl+d

Full reference

Sign up to request clarification or add additional context in comments.

2 Comments

how can i run ctrl+a+[ ? its giving error.
Error: Invalid key sequence ctrl+a+[
2

You probably should just start the command without attaching to the screen session in the first place, like

screen -d -m python manage.py runserver

but if you can't do that for some reason, you could detach from a screen session you're currently in by doing:

screen -S "$STY" -X detach

screen saves its current session info in STY, so we'll use that to make sure we're interacting with the correct session (in case there are many). Then we'll use -X to send a command to that session, in this case our command will be detach which will detach all the attached sessions, including the one used to execute that command

So while this doesn't actually send key strokes, it does highlight that there is often another command that you can send to accomplish your goals. Here detach takes the place of ctrl+a+d. Sending quit or running exit could often replace ctrl+d.

Another work-around would be to use expect which you could then use to send the strings containing control characters or hex values of them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.