7

How can I set the cursor to the beginning of line in a bash script. It should have the same behavior as pressing Ctrl-a. I tried something like this echo -e "\e[H" but it didn't work.

Here is what I'm trying to do. Let's say I have a command that I want to perform an action on it (doesn't matter what) before executing it. So I associated a Key (using bind -x ) to a function that will perform that action. However, before executing that action, I need to place the cursor to the beginning of that command (as if pressed Ctrl-a)

Walid Ber
  • 81
  • 1
  • 1
  • 4
  • 1
    `\e[H` (short for `\e[1;1H`) moves the cursor to the first line and first column of the terminal window. – chepner Mar 11 '17 at 22:59

3 Answers3

4

While Deanie's answer of

echo -ne "\r"

is correct, I found I had to ensure that my hash bang was correct:

#!/bin/bash

NOT

#!/bin/sh
Quintin Balsdon
  • 5,484
  • 10
  • 54
  • 95
3

Wouldn't it just be

echo -ne "\r"

Sorry, forgot to suppress the newline.

Deanie
  • 2,316
  • 2
  • 19
  • 35
  • It just removes the previous line. Not what I'm searching for. – Walid Ber Mar 11 '17 at 23:05
  • @WalidBer "How can I set the cursor to the beginning of line in a bash script"... this is how you can set it to the beginning of the line. What you want to ask how you set it to the "home" position which is usually the first line and first character space. – Deanie Mar 12 '17 at 03:45
  • I had to run it with #!/bin/bash and not #!/bin/sh – Quintin Balsdon Jan 18 '18 at 10:52
0

Let say want bind the /some/path to shift-alt-W and want move to the beginning of the line:

bind '"\eW":"/some/path\C-a"'

Pressing the shift-alt-w will enter the /some/path into the terminal, and the \C-A cause to move to the beginning of the line so you can type cd before the /some/path.

clt60
  • 62,119
  • 17
  • 107
  • 194
  • Is it possible to execute a function binded to my key and then move the cursor to the beginning ? If I try this `bind '"\eW":"my_function\C-a"'`, it just prints my_function. – Walid Ber Mar 12 '17 at 11:34
  • Nevermind, I just found a workaround. `bind '"\key1":"\C-a"' bind -x '"\key2":"my_function"' bind '"\eW":"\key1\key2"'. Thanks – Walid Ber Mar 12 '17 at 11:53