Skip to content

Shell

  • $PS1: prompt
  • $HOME: base directory
  • $IFS: separator
  • $0: name of the script
  • $1, $2: arguments
  • $*: list of arguments - truncated with first char of $IFS
  • $@: list of arguments - as separated args
  • $#: number of arguments
  • $?: last return code

man bash can explain a lot

#!/bin/sh
x="hello world"
# a variable without quote can be two separate arguments
printf '%s\n' $x
# hello
# world
# a variable with quote will be one argument (exception exists for $@)
printf '%s\n' "$x"
# hello world
# the $IFS char will be replaced by space
# you can also change the IFS temporarly
IFS='w'
printf '%s\n' $x
# hello
# orld
# note the space after hello and the missing 'w'
printf '%s\n' "$x"
# hello world
IFS=' ' # reset the IFS
Terminal window
# Redirect stdout to FILE - override
cmd > FILE
# Redirect stdout to FILE - append
cmd >> FILE
# Redirect stdout and stderr to FILE
cmd &> FILE
# Redirect stderr to FILE
cmd 2> FILE
# Redirect stdout to FILE and stderr to stdout
cmd > FILE 2>&1
cmd >& FILE
# The standard output of cmd is connected via a pipe to the standard input of cmd2
cmd | cmd2
# cmd's standard error, in addition to its standard output, is connected to cmd2's standard input through the pipe
cmd |& cmd2
# stdin from FILE
cmd < FILE
# string as stdin
cmd <<< "string"
echo -n string | cmd
# stdin from FILE stdout to OUTPUT
cmd < FILE > OUTPUT
Terminal window
test -f myfile # return 1
touch myfile
test -f myfile # return 0
# You can also use the test binary with the '[' binary - it's the same form
# but you need a closing ']'
[ -f myfile ]