- The character (or set, or range) to delete is given by the
-r
flags's argument, so there's no need to read
it.
- The filename (if any) is left in the positional argument after command line processing is done.
- Don't process the file when you're not yet done with processing the command line flags.
- The option string to
getopts
is backwards.
Solution:
#!/bin/bash
# Process command line.
# Store r-flag's argument in ch,
# Exit on invalid flags.
while getopts 'r:' opt; do
case "$opt" in
r) ch="$OPTARG" ;;
*) echo 'Error' >&2
exit 1 ;;
esac
done
# Make sure we got r-flag.
if [[ -z "$ch" ]]; then
echo 'Missing -r flag' >&2
exit 1
fi
# Shift positional parameters so that first non-flag argument
# is left in $1.
shift "$(( OPTIND - 1 ))"
if [[ -f "$1" ]] || [[ -z "$1" ]]; then
# $1 is a (regular) file, or unset.
# Use file for input, or stdin if unset.
cat "${1:--}" | tr -d "$ch"
else
# $1 is set, but not a filename, pass it as string to tr.
tr -d "$ch" <<<"$1"
fi
This would be used as
$ ./script -r 'a-z' file
(deletes all lowercase characters in file
)
$ ./script -r 'a-z' "Hello World!"
(deletes all lowercase characters in the given string, unless it happens to be a filename)
$ ./script -r 'a-z'
(deletes all lowercase character in the standard input stream)