Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

There are a couple of times I have been presented with some codes as solutions to problems. My question is how do write these type of scripts myself for some fairly routine tasks?

share|improve this question
add comment

1 Answer

up vote 12 down vote accepted

There is number of scripting languages available. The most common under Linux might be Bash, Phyton and Perl. They all have their advantages and disadvantages. It is a very vast field. For starters I'd recommend the Bash Guide for Beginners to learn how to automate routine tasks. Bash is ideal because it is present in almost all Linux distributions and often even the default shell - when you learn bash scripting you also learn how to use the shell very effectively. So that's a plus with Bash. Personally I like Perl the most.

What all scripting languages have in common is that you write a regular text file containing commands. These files are called scripts A script file should start with a line specifying the interpreter of your choice language (i.e. the program that executes the command in your text file). An example for this line would be this:

#!/bin/bash

That tells your computer the following lines are bash commands to be executed with bash shell. What the available commands are can be learned in the various guides.

Once you have written that file, you need to make it executable. Say your file is named foo.sh than this line in a shell would make it executable:

chmod +x foo.sh

After that you can run the script typing:

./foo.sh

hitting ENTER afterwards. A very easy example for a full script would be:

#!/bin/bash
# This script prints "Hallo world X" five times
#+where 'X' is a number from 1 to 5.
for i in 1 2 3 4 5; do
    echo "Hallo world $i"
done

And that's how I wrote and executed it in gnome-terminal, which is the default graphical terminal in Ubuntu:

enter image description here

share|improve this answer
3  
Just two points: 1. You don't strictly need to add a "hash-bang" (#!/bin/bash) line at the top of the file or make it executable - it can be executed as bash myscript.sh. 2. It may be handy to create a bin/ directory in your home folder and place your scripts there - the directory is added to PATH and the scripts will be available from anywhere –  Sergey Sep 15 '11 at 23:11
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.