CSCI 344
Beginning Bash Scripts
Write the following bash scripts. You may use the Internet as a
reference for bash script syntax and as a reference for UNIX/Linux
commands (such as grep, awk, and sed), but you may not search for
solutions to these problems--that would completely defeat the purpose
of doing these exercises.
Hint: calling sed or awk make a couple of these problems easy to solve.
Here is a link to the O'Reilly's Learning Bash. Note: this link only works sometimes and may only work from the csuchico.edu domain.
Arguments passed from the command line to a bash script can be accessed the same way as arguments passed to a function:
| $# |
the number of arguments |
| $* |
all the arguments as a single string “one two three” |
| $@ |
n separated double quoted strings “one” “two” “three” |
| $0 |
the first argument (similar to argv[0] it is the script's name) |
| $1 |
the first “real” argument |
| $2 |
the second argument |
| $3 |
... |
(1) Write a bash script called oddeven that accepts a filename as a
command line argument and splits the lines in the file into two
different output files (also command line arguments to your bash script). The odd numbered
lines (e.g. 1, 3, 5, ...) should be written to a file and the even
numbered lines (e.g. 2, 4, 6, ...) should be written to a file.
$ oddeven my_file my_file_odd my_file_even
(2) Write a bash script to display the current month, the day and the year, in the following format:
$ mydate
Day of week: Fri
Month: Feb
Day of month: 9
(3) Write a bash script that takes an input file with the form
"last,first" and creates two files, one with last name, one with first
names:
$ split input_filename last_filename first_filename
(4) Write a bash script called
rename that takes a filename that contains spaces and replaces the
spaces with a period (‘.’). Any file
that does not contain spaces in its name should be unchanged.
"one two three" would become one.two.three
$ rename one two three
$ ls
one.two.three
$
(5) Write a bash script that swaps two files
$ swap a.cpp b.cpp
a.cpp will be renamed b.cpp and b.cpp will be renamed a.cpp w/o deleting the contents of either