User Tools

Site Tools



Chaining with ;

So far, we've typically executed one command per line. However, we learned to pipe commands together, which is a way of combining two commands into one.

We can also tell the shell to execute two commands in succession. This is called chaining and it uses the ;, semi-colon.

chaining usage:
command1; command2

:!: Exercise: Try it:

$mkdir testdir; touch testfile.txt

The shell waits for the first command to finish before the second command completes. You can command multiple commands together.

Basic scripting

We can also write very basic scripts by adding lists of commands into a script.

:!: Exercise: Copy and paste the following text into a script and name it


#make a directory
mkdir scriptdir

#make a readmefile
touch readmefile.txt
  • Execute the command with either bash
  • OR make it executable with chmod, and execute it with ./

:!: Common pitfall: Comment your code!!! This makes your code readable to other users. Remember other user is you, 2 months from now.

:!: Common pitfall: Test your scripts frequently for proper behavior. Even the best programmers test their code every few lines.

Creating custom commands with alias

We can create new, customized commands out of other commands by using alias. This saves a new command for the duration of our session. You can learn how to create aliased commands that persist for more sessions by adding them to your user bash profile, covered later in the course.

Alias Usage:
alias <name>=<'string'>

  • <name> is the name of the new custom command
  • <string> is a list of commands that will be executed when <name> is executed.

:!: Common pitfall: Typically, we don't like to overwrite existing commands. Make sure to test whether <name> exists as a command first before making it a command with alias.

:!: Exercise: Try to make a new command called rmsafe:

$rmsafe #check whether this command exists already
$alias rmsafe='rm -i'
$rmsafe readmefile.txt

:!: Exercise: Let's say you find yourself doing the following operation routinely…

$grep -i 'chr' file1.txt > file1_chr_info.txt
$grep -i 'chr' file2.txt > file2_chr_info.txt

How would you make a custom command called findchr that will execute this command automatically for a new file (say, file3.txt)? What would the new command line look like?

;-) Quick tip: logging out of the terminal will remove aliases. You can also remove aliases using unalias.

Best practices

wiki/2016chaining.txt · Last modified: 2016/09/01 09:22 by erin