overview of the most useful features
the shell command language of the portable operating system interface
short: posix shell, sh
bash/ksh/zsh are sh compatible shells
a=bc
a="bc d"
no space around =
a="echo test"
$a
-> echo test
"$a"
-> "echo test"
conditions use the exit code of commands
if grep -Fq error development.log then # code elif test $? -eq 3 # code else # code fi
"true" is a program that is usually installed
while true do echo test done
"for" automatically splits the arguments after "in" at whitespace
for a in b c d e do echo $a done
for a in *; do echo "$a"; done
while true; do echo test; done
last exit code
$?
number of arguments
$#
all arguments
$@
argument 1, 2, 3, ...
$1 $2 $3
remove the first argument and move following to the left
shift
manually set the positional arguments
set -- one two three four
cd /tmp && echo test || echo xy ; echo z
left associative. evaluated like this
((cd /tmp && echo test) || echo xy) ; echo z
| execute command and connect output to standard input of the next command
the two subprocesses will be connected by a pipe, which is a type of file maintained by the operating system
the exit code of the chain is the exit code of the last command
ls -l | grep 'txt' | grep -v 'abc'
>>
create file or append to file>
create or truncate and write to file<
read from filecat filename | tail >> output-file
name() { # code ... }
name() { echo $@ }
name() { echo $1 }
note the always empty parentheses
name 3 2 1
operator argument ...
/usr/bin/echo test
./this_file
echo
the last one searches the file in directories listed in the environment variable $PATH
a=echo test $a 3
test() { tail > /tmp/output } cat filename | test
compress_javascript() { uglifyjs --compress --mangle $@ } cat input.js | compress_javascript > output.js
$@ is used in this example to be able to possibly pass additional arguments to "uglifyjs"
evaluate shell code and get what would be written on standard output as a string
$()
$(code ...)
timestamp=$(date +%s)
$((1 + 2))
#!/bin/sh # links config files to their destinations install() { sources=$@ cp --recursive --force --symbolic-link --verbose \ --target-directory=/ $sources } if test $# -eq 0 then echo usage example: ./exe/install hostname else install "$PWD/data/$1"/* fi
./filename sh filename