Unix shell basics
Rough notes for a half-hour course on Unix shell basics.
Run a program (ls)
ls
which ls
/bin/ls
cd /bin
./ls
echo $PATH
cd -
Shell variables
echo PATH
echo $PATH
PATH=~
echo $PATH
ls (!)
- put PATH back to original value
Manuals
man ls
- man uses an external PAGER program, by default "less"
- less keys (similar to vi):
h help
q quit
SPACE scroll forward
/ search
n next search hit
less ../stb-tester/stbt.py
cat ../stb-tester/stbt.py
PAGER=cat man ls
- shell builtins:
man cd
man man
man passwd
man 5 passwd
man printf
man 3 printf
- "ls(1)" means the ls manpage in section 1
man hier for a somewhat old-fashioned description of the file-system hierarchy
arguments
cat printargs.c
#include <stdio.h>
int main(int argc, char** argv) {
int i;
for (i = 0; i < argc; ++i) {
printf("--- arg %d: ---\n", i);
printf("%s\n", argv[i]);
}
return 0;
}
gcc printargs.c -o printargs
./printargs hello world
expansion
- Shell Parameter Expansion
- Single Quotes
- Double Quotes
- Does word splitting happen before or after parameter expansion?
DAVE="a b c"
./printargs $DAVE
./printargs "$DAVE"
- Filename Expansion
- Other Shell Expansions
environment variables
standard input, output & error
- Standard Input is where input data comes from, often the keyboard.
- Standard Output is where output data goes, often the terminal screen.
grep o and type "hello" (RETURN) and "there" (RETURN) (on standard input)
- Redirections
- Standard error
grep < printenv.c > main.txt You wouldn't want the error going into main.txt
- Not just for errors:
curl http://www.google.com
curl http://www.google.com > google.html
- Pipelines
job control
- http://www./software/bash/manual/html_node/Job-Control.html
sleep 600 press Control-C
sleep 600 press Control-Z
jobs Stopped
bg %1
jobs Running
man bash page down a bit, then press Control-Z
jobs
fg then press Control-Z again
sleep 700 &
jobs
kill %3 Same as sending Control-C to a foreground process
ps f
kill 1234 Give the process id of the sleep process instead of "1234"
exit code
- Just an arbitrary number to communicate exit status to the calling process
./printargs
echo $?
- Modify printargs's main function to return 42
gcc printargs.c -o printargs
./printargs
echo $?
- The shell considers a 0 exit code as success, anything else as failure.
- Also used by shell looping & conditional constructs:
if ./printargs; then echo ok; else echo failed; fi
./printargs && echo ok Short-circuiting boolean AND
man grep Scroll down to EXIT STATUS near the end
Further reading
|