Bash misc tips

Bash debugging
A nice thing to do is to add on the first line

#!/bin/bash -x

This will produce some interesting output information

Reading user input with read

In many ocations you may want to prompt the user for some input, and there are several ways to achive this. This is one of those ways:

echo Please, enter your name
read NAME
echo "Hi $NAME!"

As a variant, you can get multiple values with read, this example may clarify this.

echo Please, enter your firstname and lastname
read FN LN
echo "Hi! $LN, $FN !"

Getting the return value of a program

In bash, the return value of a program is stored in a special variable called $?.

This illustrates how to capture the return value of a program, I assume that the directory dada does not exist. (This was also suggested by mike)

cd /dada &> /dev/null
echo rv: $?
cd $(pwd) &> /dev/null
echo rv: $?

Capturing a commands output

This little scripts show all tables from all databases (assuming you got MySQL installed). Also, consider changing the ‘mysql’ command to use a valid username and password.

DBS=`mysql -uroot  -e"show databases"`
for b in $DBS ;
  mysql -uroot -e"show tables from $b"