1

I have a folder in ~ called work that contains all my work. Usually when I start an instance of Terminal I type cd work.

I would like to avoid this because it's very repetitive. I tried putting cd work in my .bashrc but I realized that I don't always want to cd work - for instance, when I Open Terminal here or when I open a Terminal in VSCode (which should open my Terminal in the current project directory, not work).

My idea is having the Terminal type out cd work whenever I open it, but not actually execute the command. If I really need to cd work, all I have to do is hit Return. However, if I don't want to do that, I can just Ctrl+C.

Is doing this possible?

a3y3
  • 113
  • 4
  • 2
    This was asked before [How to start a terminal with certain text already input on the command-line?](https://askubuntu.com/questions/5363/how-to-start-a-terminal-with-certain-text-already-input-on-the-command-line) however there are some alternative solutions [here](https://unix.stackexchange.com/questions/391679/how-to-automatically-insert-a-string-after-the-prompt) and [here](https://unix.stackexchange.com/questions/82630/put-text-in-the-bash-command-line-buffer) – steeldriver Mar 25 '21 at 23:46
  • Read `man bash`, the "INVOCATION" section. You can probably `[[ -n "$PS1" ]] && cd work`, by why not type the 8 characters? – waltinator Mar 26 '21 at 00:38

1 Answers1

1

Solution

You can use the bash built-in command read:

  • Either use it in a simple one line and add it to the end of your ~/.bashrc file like so:

    read -p "${PS1@P}cd work"; cd work
    
  • Or define a custom function and call it at the end of your ~/.bashrc file like so:

    myfunction() {
        mycommand="cd work"
        read -p "${PS1@P}$mycommand"
        $mycommand
    }
    
    myfunction
    

Information

  • read -p will show the text and wait for either Enter to continue or Ctrl+c to abort.
  • ${PS1@P} will show your current prompt before the text.
Raffa
  • 24,905
  • 3
  • 35
  • 79
  • Hmmm this comes really close. It works, but when I open a new Terminal I kinda get the text waiting for me there, without starting bash itself. Bash starts after I either press Return or Ctrl+c. Regardless, if this question doesn't get more answers, I will mark this as accepted. – a3y3 Mar 26 '21 at 00:14
  • @a3y3 It runs in bash!... Bash already in use when you see the text. Also "If I really need to cd work, all I have to do is hit Return. However, if I don't want to do that, I can just Ctrl+C."... You got what you asked for :) – Raffa Mar 26 '21 at 00:23
  • @a3y3 I updated the answer to show the prompt as well. – Raffa Mar 26 '21 at 13:51