user3226932
user3226932

Reputation: 2232

Calling multiple Bash aliases

I want to open three different folders on three new terminals from my terminal using one command. All of them should run independently of each other meaning one command does not depend on the one before it.

Here is my .bash_aliases, which is called from .bashrc

alias cmd1=gnome-terminal && cd ~/Desktop/

alias cmd2=gnome-terminal && cd ~/Documents/

alias cmd3=gnome-terminal && cd ~/Music/

alias runcmds='cmd1 & cmd2 & cmd3'

But this opens up three terminals in the Music directory and doesn't execute the commands correctly. How can I make it so that runcmds runs all 3 commands separately from each other?

Also, when do I need to use quotation marks and when do I not need to?

Upvotes: 1

Views: 671

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295363

Your order of operations is backwards: You need to cd before you start the terminals, if you want the new shells within those terminals to be impacted by the cd. Moreover, you need to quote, to ensure that both commands -- the cd and the invocation of gnome-terminal -- are considered part of the alias.

alias cmd1='cd ~/Desktop/ && gnome-terminal'
alias cmd2='cd ~/Documents/ && gnome-terminal'
alias cmd3='cd ~/Music/ && gnome-terminal'
alias runcmds='cmd1 & cmd2 & cmd3'

By the way, I'd suggest -- strongly -- not using aliases at all, and defining functions instead:

cmd1() { cd ~/Desktop && gnome-terminal; }
cmd2() { cd ~/Documents && gnome-terminal; }
cmd3() { cd ~/Music && gnome-terminal; }
runcmds() { cmd1 & cmd2 & cmd3 & }

No quoting involved whatsoever (the final &, as opposed to a final ;, prevents the parent shell's location to being changed to ~/Music by ensuring that cmd3, like the others, runs in a subshell). Of course, you could just implement one function:

runcmds() {
  local dir
  for dir in ~/Desktop ~/Documents ~/Music; do
    (cd "$dir" && exec gnome-terminal) &
  done
}

Upvotes: 4

Pandya's Bot
Pandya's Bot

Reputation: 49

Actually gnome-terminal facilitates the --working-directory option.

From man gnome-terminal:

--working-directory=DIRNAME
     Set the terminal's working directory to DIRNAME.

You can use alias as follows:

alias cmd1='gnome-terminal --working-directory="$HOME/Desktop"'
alias cmd2='gnome-terminal --working-directory="$HOME/Documents"'
alias cmd3='gnome-terminal --working-directory="$HOME/Music"'
alias runcmds='cmd1 & cmd2 & cmd3'

Upvotes: 3

Related Questions