Change to a directory using a bash menu script and launch vscode

by | Sep 19, 2018 | IT Tips

This is a shell script that changes to my code development directory and then lists the directorys and gives a numbered menu to enter a number and then change to that directory and launch vscode

You need to add an alias to your .bash_profile so that the script is sourced instead of being run in a new process. (remember to source your ~/.bash_profile to make the alias active)

Menu Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<span class="hljs-meta">#!/bin/bash
</span>
<span class="hljs-comment"># /usr/local/bin/smenu.sh</span>
 
PS3=<span class="hljs-string">'Please enter your choice: '</span>
 
<span class="hljs-comment"># change to my development directory</span>
<span class="hljs-built_in">cd</span> ~/sites || {
    <span class="hljs-built_in">echo</span> <span class="hljs-string">"Directory doesn't exist exiting"</span>
    <span class="hljs-built_in">kill</span> -INT $$
}
 
QUIT=<span class="hljs-string">"Quit"</span>
 
<span class="hljs-comment"># glob for directories only</span>
options=(*/)
<span class="hljs-comment"># add the Quit option to the end of the array</span>
options+=(<span class="hljs-variable">$QUIT</span>)
 
<span class="hljs-comment"># create the select menu</span>
select opt <span class="hljs-keyword">in</span> <span class="hljs-string">"<span class="hljs-variable">${options[@]}</span>"</span>; <span class="hljs-keyword">do</span>
    <span class="hljs-keyword">case</span> <span class="hljs-variable">$opt</span> <span class="hljs-keyword">in</span>
    <span class="hljs-comment"># do something different if they choose quit</span>
    <span class="hljs-variable">$QUIT</span>)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"Quitting without changing directory"</span>
        <span class="hljs-built_in">break</span>
        ;;
 
    <span class="hljs-comment"># otherwise default is change directory</span>
    *)
        <span class="hljs-built_in">echo</span> <span class="hljs-string">"Changing Directory to <span class="hljs-variable">$opt</span> (<span class="hljs-variable">$REPLY</span>)"</span>
        <span class="hljs-built_in">cd</span> <span class="hljs-variable">$opt</span>
                vscode .
        <span class="hljs-built_in">break</span>
        ;;
    <span class="hljs-keyword">esac</span>
 
<span class="hljs-keyword">done</span>

Line to add to .bash_profile

1
2
<span class="hljs-comment"># in ~/.bash_profile</span>
<span class="hljs-built_in">alias</span> smenu='. /usr/<span class="hljs-keyword">local</span>/bin/smenu.sh'

0 Comments