2
vishex ()
{ 
    echo '#!/bin/bash' > $1;
    chmod +x $1;
    vi $1
}

The goal of the above function is to have an alias for fast and comfortable creation of bash scripts. I would like that at the opening of the file the cursor would be not standing in the Shebang line but on a line below. I've tried something like echo 'blabla\n', echo "blala\n", printf "blala\n" without any result.

  • change echo '#!/bin/bash' > $1; to echo -e '#!/bin/bash\n' > $1;. Then follow Radovan's answer – Lambert Oct 9 '15 at 7:40
  • 4
    One day you will regret this when you vishex mygreatscript.sh and lose dozens or hundreds of lines of code. You are tempting Murphy. So start the function with [ -e "$1" ] && return 1 – cas Oct 9 '15 at 7:40
  • @cas It's easy to avoid this if add check [ -f "$1" ] && exit 1 – Costas Oct 9 '15 at 7:45
  • For a function, you want return, not exit (or bye-bye shell). Or do it as chaos did it in his answer. – cas Oct 9 '15 at 7:47
3

Use this:

vishex () 
{ 
    [ -e "$1" ] || echo -e '#!/bin/bash\n\n' > "$1";
    chmod +x "$1";
    vi "+normal G" +startinsert "$1"
}
  • [ -e "$1" ] checks if the script already exists. If yes echo will not override it.
  • -e in echo enables interpretation of backslash escapes, such as \n for a newline. Then it inserts 2 newlines after the shebang line.
  • +normal G runs the ex command G which jumps to the last line in the file.
  • +startinsert switches directly to insert mode (you can also leave that, as it's not in the question mentioned).

So, when executing vishex script it looks as follows:

#!/bin/bash

<- cursor is here
~
[...]
~
-- INSERT --                                                               3,1           All
| improve this answer | |
0

Assuming your vi is actually vim, from the manpage:

+[num]   For  the  first file the cursor will be positioned on line "num".
         If "num" is missing, the cursor will be positioned  on  the  last line.

Thus, use:

vi + "$1"
| improve this answer | |
  • 1
    Actually this was a feature in the original vi as well, IIRC – wurtel Oct 9 '15 at 10:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.