Shell scripting goodies
I finally decided to create a page devoted to all the little nuggets of shell scripting goodness I put to use regularly. Why repeat it, when you can script it? Nothing cohesive here, just little snippets and functions I find useful, hopefully someone else does too.
1. Script whereami
This one should be intrinsic, but have you ever needed a script to be “aware” of where it was executing from? These sort of things keep me up at night. This is less of a trick than a reminder, because I always seem to forget this.
$base will be populated with the current execution directory of the script, that way you can reference scripts in the same directory as the script that is currently executing.
path=$(dirname "$0") base=$PWD/$path/
2. Here document kung-foo.
I use here document statements a lot in my shell scripts. It’s nice for them to 1) retain indenting; 2)optionally expand variables; 3) redirect into a file; 4) do it all as root, and/or 5) feed a series of commands into a program;
Standard here doc
echo << EOF No indenting here! Variables will be expanded EOF
Retaining indenting (add a ‘-‘ after the LimitString) and not expanding variables, use single quotes
echo <<- 'EOF' Indenting will be retained $Variables are not expanded EOF
Retaining indenting, not expanding variables and outputting to a file
echo <<- 'EOF' > /tmp/file.txt Indenting will be retained $Variables are not expanded, and I am going to end up in a file! EOF
Retaining indenting, not expanding variables and outputting to a file with root permissions
echo <<- 'EOF' | sudo tee /tmp/file.txt Indenting will be retained $Variables are not expanded, and I am going to end up in a file! EOF
Feed commands to a program, not all programs support this
ftp -i -n -v << EOF open $ftpServer user $ftpUser $ftpPass prompt put $myFile quit EOF