More on Bash Scripting

1. For anything that don't needs to be escaped a lot, sudo sh -c is good enough.

2. I've not even to begin to explore the power of sed, the stream editor. Example here is to insert a line to the beginning of a file. More reading on the one-line scripts for Sed in coming months.
$ sudo ls -l /root | sudo tee /root/ls.txt > dev/null
$ sudo sh -c 'ls -l > /root/ls.txt'

3. "Syntax error: "(" unexpected". That's the error you got when you tried to run a Bash script through Dash without the shebang line, which is the default system shell for Ubuntu or Debian.

4. It will take a while to appreciate the concise syntax of Bash. Let's look at these two examples [9] where we restart a daemon upon a missing file.

Ex1: Typical version
if [ ! -f /tmp/daemon.pid ]; then
python daemon.py restart
fi

Ex2: Concise version
[ -f /tmp/daemon.pid ] || python daemon.my restart

The [] constructor check the existence of the file and return *0 on success* and any number than 0 as failure. Yup, zero as success status compare to other popular programming language. Reason is you can return many different codes as error status but only one code to represent success.

Meanwhile, the || construct will execute the command on the right only if the command on the left fail.

No comments:

Post a Comment