Shell Tips

booleans:

DOTOUCH=true
$DOTOUCH >> touch $SIGFIL


find extension of filename:

$filename="test.file.jpg"
...
EXT=${filename#*.}	# gives ".jpg"
BASE=${filename%.*}	# gives "test.file"


String replacement (once and multiple):

$startstring="This is some nice text."
NEW="${startstring/nice/different}	# gives: This is some different text.
NEW="${startstring//i/a}"		# gives: Thas is some nace text.
Special handy: remove superfluous spaces:
x="This   is a spacious     string"
y=${x/ /}
echo $y
This is a spacious string


command substitution:

FOUND=$(grep searchpattern $(find . -name filename) 2> /dev/null)
This supports nesting (backticks do not)


parameter default:

PARAMETER=${uservalue:-defaultvalue)
If uservalue is empty OR not defined, results in defaultvalue


compare file-times:

FILE1=...
FILE2=...
FILETIME1=$(stat -c %Y "$FILE1")
FILETIME2=$(stat -c %Y "$FILE2")
if [ $FILETIME2 -lt $FILETIME1 ]
then
	...
stat option %Y gives modification time in seconds since epoch


delete unnecessary files:

find . -name Thumbs.db -print0 | xargs --null rm -f
-print0 makes 'find' and 'xargs' work with null-terminated strings, so accept filenames with spaces and <CR>-characters.

find large files (>1GB):
or:
find . -mtime +31 -name Thumbs.db -exec rm -f {} \;
find / -size +1000000k -xdev | xargs ls -lh
or:
find / -size +1000000k -xdev | xargs -i ls -lh {}
(-i: means inline replacement / {} will be replaced )


find problems with E-mail:

egrep '(reject|warning|error|fatal|panic):' /var/log/mail.log


Check in a logfile what happend yesterday:

fgrep -e "`(export TZ=FJH+24; date "+%a %b %e")`" some-logfile


Print the number of bytes used in the current directory:

ls -l | awk 'BEGIN { c=0 }{ c+=$5 } END { print c }'


Make your script behave nicely:

renice +19 -p $$


Append stderr to stdout:
Append stderr to stdout to file:

2>&1
bad_command >>filename 2>&1