msgbartop
A chronological documentation test project, nothing serious, really!
msgbarbottom

20 May 2007 Bash misc tips

Posted by

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:

#!/bin/bash
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.

#!/bin/bash
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)

#!/bin/bash
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.

#!/bin/bash
DBS=`mysql -uroot  -e"show databases"`
for b in $DBS ;
do
  mysql -uroot -e"show tables from $b"
done

Source: http://en.tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-10.html

Tags: ,

Comments are closed.