#Basics
writing output with no \n at the end
echo -n 'something with no newline'
redirecting stdout and stderr to the same file
both >& outfile
A hyphen indicates that input is taken from the keyboard. In this example, to create a new file file2 that consists of text typed in from the keyboard followed by the contents of file1
cat - file1 > file2
read user input read -p "prompt" READED
Take Y/N from user and switch functions to execute accordingly
# cookbook filename: func_choose
# Let the user make a choice about something and execute code based on
# the answer
# Called like: choose <default (y or n)> <prompt> <yes action> <no action>
# e.g. choose "y" \
#
"Do you want to play a game?" \
#
/usr/games/GlobalThermonucularWar \
#
'printf "%b" "See you later Professor Falkin."' >&2
# Returns: nothing
function choose {
local default = "$1"
local prompt = "$2"
local choice_yes = "$3"
local choice_no = "$4"
local answer
read -p "$prompt" answer
[ -z "$answer" ] && answer="$default"
case "$answer" in
[yY1] ) exec "$choice_yes";;
# error check
[nN0] ) exec "$choice_no";;
* ) printf "%b" "Unexpected answer '$answer'!" >&2;;
esac
} # end of function choose
Positional command-line args
$*
means all input args. use $1, $2, ..
to refer to each arg. e.g.:
for f in $* ; do
echo changing $f
chmod 750 $f
done
Handling filenames with blanks: use double-quotes around variables "$*" "$@"
Setting default-values for script args FILENAME=${1:-/tmp}
. Use {:-}