Week 8 workshop exercises

Shortcuts for commands – aliases

Try typing the following at the shell:

$ alias longlist="ls -l"

What happens if you then type longlist .? Or longlist, and some other directory?

What happens if you now type alias on its own?

This is called an alias – see help alias for more details on these.

If there are multiple aliases you always wish to use, they can be put in the file .bashrc in your home directory – the commands in this file are executed every time you invoke bash.

Try adding:

echo "in bashrc"

as the last line in .bashrc. Then enter a new shell level by typing bash, and confirm this command executes. (You can also confirm the environment variable SHLVL has increased by one.)

Shortcuts for commands – functions

Create a new script file, say myscript.sh, and make it executable using chmod.

Add the following (after the hash bang line):

function myloop {
  for i in 1 2 3 4 5; do
    echo hello, number $i
  done
}

myloop

This is an example of a function, and a call to that function.

Now, try amending your code so it looks like the following:

function myloop {
  local message="$1"
  for i in 1 2 3 4 5; do
    echo $message, number $i
  done
}

myloop goodbye

Here we have passed parameters to our function. Passing parameters looks very much like supplying arguments to a command; on the “inside” of the function, we can access arguments as variables called $1, $2, $3 and so on.

Exercise: amend myloop so it takes a custom starting number, a custom ending number, and a custom message. (Hint: you may want to use a while loop, rather than a for loop. Or, you can use an alternative for loop syntax, which looks like this:
for ((i=1; $i<5; i=$i+1)); do echo $i; done. Typing help 'for ((' gives some information on this syntax.)

“Here” documents

Put the following in a new script file (after the hash-bang line):

grep wolf <<HERE
wolf
lion
zebra
jackal
HERE

Experiment with giving grep different arguments instead of “wolf”. This is called a “Here” docuent, or “heredoc”. We can actually use any label we like instead of HERE – try “THERE”, for instance – but it is conventional to use capital letters to make the label stand out easily.

If we want to use the result of a heredoc in a variable, we can try something like:

myvar=$(cat <<HERE
some
text
HERE
)

echo "$myvar"

This provides a way of writing multi-line messages more easily in bash. Here documents can be used with any command that accepts standard input.

Exercise: use a here document to run a series of commands on an ssh server – for instance, print the working directory, then list its contents.