Search code examples
linuxbashgnome-terminal

Bash script to open a terminal and cd to a variable directory


I want to write a bash script that opens a gnome-terminal in a directory in ~/Documents/ according to the argument passed to it (e.g. ./open.sh notes opens the terminal in ~/Documents/notes/)

How would I go about that? I know gnome-terminal --working-directory=[directory] does something similar, but it doesn't accept strings so I don't know if it can be used in this case.


Solution

  • you can try this;

    #!/bin/bash
    workDir="/home/user/Documents/$1"
    if [ ! -d "$workDir" ]; then
        echo "directory not found, check your path"
    else
        gnome-terminal --working-directory="$workDir"
    fi
    

    Example;

    ./open.sh notes
    

    this open a new terminal in ~/Documents/notes