Geek Lair

Archive for the ‘bash’ Category

Bash script to compile and run a C program in one step

with 3 comments

Here is a simple script to compile and run a C program:

#!/bin/bash
# Script to compile and execute a c program in one step.

# Get file name without the .c extension
file_name=$(echo $1|sed 's/\(.*\)\.c/\1/')

# Compile the program with -o option to specify the name of the binary
gcc -o $file_name.out $1

# If there were no compilation errors, run the program
if [[ $? -eq 0 ]]; then
        ./$file_name.out
fi

The same could be done for C++ programs as well. Just replace the .c in the sed expression with .cpp and replace gcc with g++

Advertisements

Written by anonir

October 26, 2009 at 18:21

Posted in bash, Linux

bash and cron

leave a comment »

Setting up cron in Ubuntu is simple enough as described in the Ubuntu wiki. But what they don’t mention is that by default cron uses /bin/sh for its SHELL env variable. That may cause a problem if you try to set up a bash script in cron. To prevent that from happening, you need to define the SHELL variable for your user crontab to point to /bin/bash.

In the console type:

crontab -e

Add the following line at the top:

SHELL=/bin/bash

Your crontab should look something like this:

SHELL=/bin/bash
# m h  dom mon dow   command
*/5 * * * * /usr/local/bin/my_bash_script

Written by anonir

October 13, 2009 at 15:45

Posted in bash, Linux, Ubuntu

Tagged with ,