cs-tech-primer

Computer Science tech primer for the University of Manitoba.

View on GitHub

Advanced shell usage

Learning outcomes

After doing this unit, students should be able to…

Moving around a line

Mash-hand-hold technique

If you’re holding down the arrow key, you’ve already messed up. Remember: home row is fastest!

Shells usually follow the readline commands, which is actually how emacs moves around, but is configurable.

Highlights

Wow, that’s easy to remember, and is far faster than holding down the arrow keys.

Other useful movements:

And, finally, clearing the line. It’s really tempting to do ctrl-c, which works, but moves down a line.

Luke, use the stack

Imagine: You have a shell, you want to do something, then come back to where you started.

Examples of this (common) scenario:

Well, then you want to use a stack structure, right? Go to the previous spot you were? Well, the unix environment agrees with you.

That was confusing… let’s go for an example:

falcon.cs.umanitoba.ca 103% pwd
/home/cs/staff/robg/demo
falcon.cs.umanitoba.ca 104% pushd /import/share
/import/share ~/demo 
falcon.cs.umanitoba.ca 106% cd man
falcon.cs.umanitoba.ca 107% pwd
/import/share/man
falcon.cs.umanitoba.ca 108% ls
CACHEDIR.TAG  cat1  cat2  cat3  cat4  cat5  cat6  cat7  cat8  cat9 [...trimmed]
falcon.cs.umanitoba.ca 109% popd
~/demo 
falcon.cs.umanitoba.ca 110% pwd
/home/cs/staff/robg/demo
# back to where we came from!

Which interpreter to use

In UNIX, we can set which program we would like to interpret the file if it is set to be executable. The file would likely be a program if it was executable!

The hash bang line goes on the first line of the file:

#!/usr/bin/python

print('hello world')

This looks like a comment to scripting languages, but has special meaning when executing a file.

Technically, the #! characters map to the ELF magic number of the file, but thats, more technical that we actually require…

The shell will invoke the interpreter specified, and pass it this file to process.

But, that is not portable! Not every installation of perl, python, bash, etc, will be in the same place on the filesystem.

But, env generally is available… and can loop up interpreters for us on the PATH.

#! /usr/bin/env python

Will search for python in the PATH, meaning that where ever the python executable is, it will be found and executed. There is more discussion in the env man page, or also on gnu’s documentation.

Strings, and ‘ vs “

Bash treats ‘ and “ differently, and it is a pitfall for new users!

Single quotes are literals - and whatever you type is kept verbatim. Which, is good…. usually… if you want that.

Double quotes will allow us to place variables in the string, which will resolve to whatever is stored in the variable.

Words are hard, examples are good:

bash-4.2$ name="Maynard"
bash-4.2$ echo "$name James Keenan"
Maynard James Keenan
bash-4.2$ echo '$name James Keenan'
$name James Keenan