Skip to content

Instantly share code, notes, and snippets.

@co89757
Last active August 29, 2015 14:06
Show Gist options
  • Save co89757/91fe79f00ecfdb65cd50 to your computer and use it in GitHub Desktop.
Save co89757/91fe79f00ecfdb65cd50 to your computer and use it in GitHub Desktop.
linux bash notes

#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 {:-}

Linux Commands You should know

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment