Lecture Notes

Learning assistant supported notes for CS 35L


Project maintained by UCLA-CS-35L Hosted on GitHub Pages — Theme by mattgraham

Common Shell Commands for Text Manipulation


Aside. This section will be updated once I have a clearer idea of Professor Eggert’s favorite commands.


Shell Commands for Filesystem Interaction

File names in Linux are of the form /A/B/C/D..../Z.

When you create a file, its owner is you (the creator), and its group is typically inherited from the group of the parent directory; (this isn’t always true but is good enough for now).


Aside. Unix style filesystems typically organize users under the directory /home. Each username will be listed as a subdirectory e.g. /home/ericwang would be a directory contain all of my files! This is not how SEASnet does it.

When you log in, your current shell session automatically sets $HOME to be whatever directory you login to. You can also refer to this variable as the tilde (~).


I/O Redirection

One of the shell’s purposes is configuring the environment for programs to be run together. A file descriptor is just a number that allows your program to interact with a file on your system. For example, when you open a file in a program, internally, your program acquires a new file descriptor e.g. 3.

The standard input (stdin), standard output (stdout), and standard error (stderr) are automatically created. In general, we can think of these are the common way of interacting with most programs.

I/O redirection is a form of interprocess communication: processes can exchange information through their inputs and outputs. By default, programs accept input from stdin, product output in stdout, and log error messages in stderr. We can change this behavior:

These can be combined and used in conjunction.


Aside. A lot of these shell operations with commands can be rewritten in terms of each other. Professor Eggert has recently taken a liking to asking questions of this nature.

As a challenge, try rewriting >&word without the ampersand. See the documentation for a solution! https://www.gnu.org/software/bash/manual/html_node/Redirections.html


Aside. You can create new file descriptors in the shell by referring to the sequentially (e.g. the next file descriptor that is available is 3). Subshells inherit file descriptors from the original process. See the LA Week 1 Worksheet for an example.

These two topics (new file descriptors and setting up the environment of a subshell) are included as an aside since I am not sure how in depth Professor Eggert wishes to talk about this!


Parallelism

Some parallelism is already achieved by |. Instead of waiting for the first command to finish before piping the output, as each write occurs in the original command, the next command can read!

If we want something to run in the background, use &.

#!/bin/bash

sleep 10&
pid=$!
wait $pid