Selected topics from Chapters 24 and 25.
- Shell scripts.
- Executable text files containing a series of commands.
- Execute by simply running the commands.
- Exactly the same commands are available command-line and script.
Some are just more useful in one place or the other.
- Making a script.
- Make text file.
- First line is #!/bin/bash
- Additional lines are commands.
- Lines starting with # are comments.
- Chmod the file executable (and readable).
- Run the file by typing its name.
- Must be on the PATH to use the simple name.
- Can run with absolute path.
- Use ./filename from the same directory.
- No particular extension needed.
- Usually just none.
- If one is used, .sh is conventional.
# This is a shell script
echo "Hello, World!"
- Where to put shell scripts?
- On the PATH, in the usual places for executables, /bin,
/usr/bin, /sbin or /usr/sbin.
- Local executables (script or not) often put in /local/bin,
/usr/local/bin, /local/sbin or
- Personal executables in ~/bin.
- Create the directory.
- If needed, add to PATH in .bash_profile
- Set and use as we know
echo "Frank is $frank"
- Variables often set using substitution
lsloc=$(which ls | tail -1)
- Configuration variables like $USER and $HOME
are available and often useful.
- Some pre-defined variables:
|$1, $2, $3, …||Each command-line argument|
|$*||All the command-line arguments|
|$@||All the command-line arguments, quoted|
|$#||Number of command-line arguments|
|$0||Name of the script|
- Here Documents
- A form of I/O redirection from the text of the script itself.
This text will be read by cat,
and sent to standard output
cat << DONE >somefile.txt
This text will be read by cat and written
to the file called "somefile.txt".
Note that any ending string can be used.
- Using <<- instead discards leading tabs on each line.