Thursday, March 31, 2005

Bash - Using statements in conditions

To test the success or failure of a command, the general method of scripting is as follows:
#!/bin/bash

some_command
if [ $? -eq 0 ]
then
    # Command executed successfully
else
    # Command execution failed
fi
A better method to do the same is as follows:
#!/bin/bash
if some_command
then
    # Command executed successfully
else
    # Command executed failed
fi
Please note the change in syntax for if between the two statements.
This can be very helpful especially if there is a chance that some line gets added between the command and the if statement. In the former case, we will effectively be checking for the return value of the new statement that has been added. In the latter case, such problems do not come.

Thursday, March 17, 2005

Bash - How to append stdout and stderr to the same file?

What happens when we use >> for redirection. This operator opens the files in append mode and hence there are no issues due to overwriting values. But try this:
#!/bin/bash

exec >>foo 2>>&1
echo hello >&1
echo boss >&2
Try making it this way:
#!/bin/bash

exec >>foo 2>>1
echo hello >&1
echo boss >&2
Now you see that the file 1 is created with the text boss. So, the bottom line is >> cannot be used with &.

Bash - How to redirect stdout and stderr to the same file?

There is a difference between giving:
$ command >file1 2>file1
and
$ command > file1 2>&1
In the former case, the two redirections maintain two different file handles and hence the data might not be what we expect it to be.
Try the following in a script:
#!/bin/bash

exec >foo1 2>foo1
echo hello >&1
echo boss >&2
In the latter case however, the two redirections share the same handle. Hence this is preferred for most purposes.
Try the following in a script:
#!/bin/bash

exec >foo2 2>&1
echo hello >&1
echo boss >&2
Now try cat of foo1 and foo2 to see the differences.
I will discuss how this happens in a different post.