Shell Scripts
- Clearly, having a script, something to allow you to replicate
a series of commands, is of value (yes, despite the proliferation
of systemd!)
- Automation can be automated by cron/anacron
- Bash (of the Bourne shell family) is pretty much the leader
- Shell scripts are less powerful than more general languages like Perl/Python; however, Perl/Python can be heavily dependent on libraries, whereas Bash is not
Bash: General features
- Best source of information is "man bash" or the Bash manual; also, see my notes from COP3353 at here and here.
- Command line editing
- History
- Pipes and redirection (| > < N> <N &&)
Bash variables and quoting
- Variables are just declared (though there's more than just that; see man bash to sample the large number of variations -- look at Parameter Expansion in the man page) ; can be "exported" to the environment so that
child processes can use them
- Double quotes versus single quotes
- Back-ticks and $()
Common filters
- sort (particularly sort -u)
- cut / paste
- uniq
- find
- head
- tail
- grep (grep -i -v)
Scripting in Bash
- #!/bin/bash hack
- chmod needed
- bash -x
Scripting in Bash
- Debugging with echo
- command-line arguments $1, $2,... $*
- $$ and $?
Alternation in Bash
- function NAME { }
- Existential tests: -d -e -f -s -w
- String tests: x = y ; x != y ; x < y ; x > y
- Numeric tests: x -eq y ; x -ne y ; x -lt y ; x -gt y
- if elif else fi
- case
Iteration in Bash
- for of two varieties
- while do done
Perl-like/Grep-like regexes
- Globs are not regexes
- . [] ^ $ \w \s \d | * ()
- ? * + {n} {n,} {n,m}
Regexes
- Globs are not regexes
- . [] ^ $ \w \s \d | * ()
- ? * + {n} {n,} {n,m}
Perl
- Getting long in the tooth, but still useful; Perl6 should be coming out soon
- Best reference: My 3353 notes and here
- Despite your text's slighting of Perl's objects on page 66, the design does have some rather nice features though Data::Dumper quickly becomes a necessity when working with them
Python
- Certainly quite popular as we saw earlier, and growing more so.
- Quite readable, though not to everyone's taste in whitespace semantics or verbosity
Best practices
- Have a usage message and support -?, --help (NOT -h!)
- Sanity checks (Perl, for instance, supports taint checking)
- Check and use error code returns
- Use reasonable variable names
- Initial (if not semantic) comments (look at the rapidly dwindling SYSV init scripts
- Avoid setuid scripts. Run them as root instead of having setuid root.
- Errors to stderr, not stdout
- Name of the program (and routine, if appropriate) that's having an error