Programming in Linux

Rob

Administrator
Staff member
Joined
Oct 27, 2011
Messages
1,263
Reaction score
2,430
Credits
3,941
Tools for Programming

At the risk of starting a flame war with Vi lovers, I'm an unconditional Emacs fan. For me, Emacs is the ideal editor for doing any kind of programming work. There are several add-ons for Emacs that will make your life much easier. One of them is Espen Skoglund's auto-header.el. This will create a header for your code files which Emacs will automatically populate with necessary information. It will also update the header each time you make changes. It's something that comes in really handy for me.

I have a subdirectory in my home directory for emacs odds and ends. I just placed auto-header.el in this directory and then modified my .emacs file like so:
Code:
(add-to-list 'load-path "~/elisp/")
(require 'auto-header)

There is a section of the auto-header.el file that defines the characters that are used for commented areas for different programming languages. The headers for the file need to be inside a commented region at the beginning of yoursource code file. The file includes 20 different programming languages, but PHP, which I use a lot, is missing. So I just added an entry for it between Perl and Postscript:
Code:
(perl-mode      . ("#"    ""    "##"  "#"))
(php-mode . ("/*" "*/" " *" "*"))
(postscript-mode . ("%" "" "%%" "%"))

Now, my files begin with a nice, auto-updating header that looks like this:
Code:
/*********************************************************************
* Filename:      listing.php
* Description:  Script to list stuff
* Author:        Michael Jordan <[email protected]>
* Created at:    Tue Nov 29 20:13:14 2005
* Modified by:  Michael Jordan <[email protected]>
* Modified at:  Tue Nov 29 22:58:56 2005
********************************************************************/


Actually, you can add more info to this header. Just consult the comments in the auto-header.el file itself for more information on that.

Programming Languages and Linux

The is a virtual smorgasbord of programming language compilers available for Linux. Just the famous gcc compileritself will create binaries for code written in, C++, Fortran and ADA as well as interpreting Java code. There are freely available compilers for other popular programming languages like Pascal, COBOL and Lisp. As you can see, there are really too many to go into all of them in any depth. Besides, this writer can't program in the vast majority of them anyway. But in this lesson, we will be looking at some of the most common scripting languages that run under Linux.

Programming with BASH

Thought it might sound like it, BASH isn't one of those captions that pop up (along with Ooff! and Biff!) when Batman and Robin are fighting the bad guys on the old 60's TV show. BASH actually stands for Bourne Again Shell. The reason for the name goes back to Steve Bourne who wrote the original Bourne Shell for Unix. When the GNU created a Free Software equivalent, they named it after Steve's shell and added a little pun on his last name.
If you're a system administrator, making BASH scripts is going to be one of those mandatory things. But far from being a chore, you'll learn that it's going to make your work and your life a whole lot easier.

Our First BASH Script

The first thing that a BASH script needs is the proverbial 'shebang'. These are two characters:

Code:
#!

Following this, you should include the path to the BASH interpreter. So the first line of your script should look like this:
Code:
#!/bin/bash

If your default shell is BASH, the line:

Code:
#!/bin/sh

does the same thing. It's just a symbolic link to /bin/bash. But if your default shell isn't BASH, you won't be invoking /bin/bash if your write a shell script with that first line. Since on Linux systems, BASH is normally the default shell, you'll see most BASH scripts start with
Code:
#!/bin/sh

From there on, you're free to do what the shell allows. Shell scripts created for administration purposes (which are the majority of scripts) are made up of lines that invoke other commands. Let's look at a simple example. Let's say you have email users on your system but you don't have a quota in place. Still, you want to monitor the sizes of the mailboxes to make sure that people aren't taking up more space than they should. This script, run from crontab, would do the trick nicely:
Except for the shebang, comment lines start with #
Code:
#!/bin/sh
 
# show us the size of email spools email spools
 
# date in YYYY-MM-DD format
today=`date +%Y-%m-%0e`;
 
# subject and recipient variables
subject="Mailcheck";
sendto="[email protected]";
 
cd /var/spool/mail
 
ls -lSh | awk '{print $5, $9}' | grep "(G|M)" | mail -s $subject-$today $sendto
 
# end script


First off, you'll see that we've declared some variables. These variables are not prefixed by any characters when declared but they are prefixed by the dollar sign ($) when used. You've also noticed that variables can be other commands, as in this example with the date command. When you use a command as a variable, it must be put inside backticks (` `).

First, the script changes to the directory where the mail spools are located. The the scripts performs an 'ls' with options and presents a list where the biggest spools are displayed first with their size in human readable format. This is piped to awk, which sorts out the size and the user name. The awk output is grepped for those spools which are in the Megabytes and Gigabytes. This is then piped to the 'mail' command and sent to the admin account with the subject plus the date we declared in those variables. The admin will then have a nice sorted list of who is using the most space in /var/spool/mail.

Built in Variables

Though we created our own variables in the previous example, BASH also comes with what are known as built invariables. Here is an example of a script with frequently used built in variables.

Code:
#!/bin/sh
 
echo "You are user $UID on $HOSTNAME"
echo "Your home directory is: $HOME"
echo "$HOSTNAME is running $OSTYPE"


The output of this script should yield something similar to this:
Code:
You are user 500 on penguin.linux.ork
Your home directory is: /home/mike
penguin.linux.ork is running linux-gnu


As you can see, we didn't have to previously declare any of these. That's why they're known as built-in variables. Their use will save you a lot of time in writing your scripts. You can find a complete list of built-in variables in theGNU BASH Reference Manual

Interactive Scripts

Though we mentioned that the main use of BASH scripts is for automating administrative tasks, there may be times when you need users to interact with scripts. If you want a user to input information, you need to use the variableread. Let's take a look at the following example:

Code:
#!/bin/sh
 
echo -n "Enter the name of a city: "
read CITY
echo -n "$CITY is "
case $CITY in
London | Paris | Berlin | Rome) echo -n "in Europe";;
'New York' | Chicago | Washington) echo -n "in The USA";;
Tokyo | Bejing | Bangalore) echo -n "in Asia";;
*) echo -n "some place - but I don't know where";;
esac


As you can see, we've declared a variable that's going to depend on what the user types in when he/she is prompted for the name of a city. After, we have several options for each case. If the user types in the name of a city we've contemplated here, he/she will be given a message as to where the city is. If not, the script will display a message that it doesn't know where the city is. Any answer is represented by the asterisk (*)

Making Sure You Have What You Need
If you have to manipulate the contents of a file, it's a good idea to check if this file exists first. Here is a simple BASH routine to do this using the if command:
Code:
#!/bin/sh
 
if test -f /var/log/mail.log; then
 
printf "The file existsn";
 
fi


This is a good idea, as it would render your script useless if you had it set to manipulate a file that didn't exist.

If Loops: A Practical Example

I was a full-time English as a foreign language teacher for 12 years, so I can't resist giving you this example of a multiple-choice test using a BASH script.
Code:
#!/bin/sh
 
PS3="Choose the number of the correct word to fill in the blank: "
echo "The emergency brake let go and car rolled ______ the hill"
 
select SENT1 in up down along beside
 
do
 
    if [ "$SENT1" == "" ];  then
        echo -e "You need to enter somethingn"
          continue
   
 
    elif [ "$SENT1" != down ];  then
        echo -e "Sorry. Incorrectn"
        echo "1. Incorrect" >> eoiexam.dat
 
    elif [ "$SENT1" == down ];  then
        echo -e "Great!n"
        echo "No. 1 - Correct" >> eoiexam.dat
        break
 
fi
 
done


The script makes use of the 'elif' routine to sort out answers that aren't correct. You will also notice that it writes the results, whether correct or not, to a file.
If you're in the teaching profession, you could expand on this to give your students a quick quiz.
 


Nice post. Personally, I'm a Korn shell user. Been using it since the '90's.
 
Nice post. Personally, I'm a Korn shell user. Been using it since the '90's.

During the time that KoRn was popular...

Anyways, OP, I think your charge that emacs is the best text editor for programming is very interesting, and i will try it out myself. I still use gedit since it's simple enough.
 
What I love about shell scripting is programs I wrote in the '90s still run like new. I'm pretty sure that goes for most shells.

ksh is where KoRn got their name. :) I didn't know about them till much later.
 
Last edited:
What I love about shell scripting is programs I wrote in the '90s still run like new. I'm pretty sure that goes for most shells.

ksh is where KoRn got their name. :) I didn't know about them till much later.

oh yeah...honestly, for that genre, i think they weren't so great. And i hear you about shell scripting, i've had a lot of fun with it so far. Overall I think linux is more stable than those corporate operating systems anyway, not in terms of bugs because every linux OS has had a lot, but in terms of open-source principal and simplicity. There are so many damn programming languages, luckily shell commands will probably never be deprecated since linux depends on them.
 
Yea, I didn't think they were that great either, but my kids were into them, well... they were kids. LOL
If shell commands ever get depreciated, I'll be out of a job. But then again, I'll be retiring in a few years anyway. I totally agree on the corporate OS's. Let's hear it for OS2 :0 I've dabbled with a few languages, but always come back to shell scripting. It just works. It's in plain text and readable by anyone. It's not too convoluted or too hard to understand.
 
Because of this thread, i've spent a couple of hours learning how to use emacs, and i think it's awesome. Unfortunately i had some buffering issues (it took a while to figure out what was going on, haha), anyone know how to clear your entire buffer? I've found this page, don't know if anything on here does that, as i don't understand what everything does yet:


does this actually clear everything buffer related?

Code:
0  2  *  *  *  /path/to/clearcache.sh
 
Because of this thread, i've spent a couple of hours learning how to use emacs, and i think it's awesome. Unfortunately i had some buffering issues (it took a while to figure out what was going on, haha), anyone know how to clear your entire buffer? I've found this page, don't know if anything on here does that, as i don't understand what everything does yet:


does this actually clear everything buffer related?

Code:
0  2  *  *  *  /path/to/clearcache.sh
I think you're getting a bit confused.
In this context, you don't want to be messing with RAM Cache's or clearing system buffers, or messing with swap space. You're dealing with buffers in emacs. A completely separate topic.

In emacs, where it talks about buffers - it's talking about the buffer for the file.
This should clear up any confusion:

And regarding clearing a buffer:

And removing buffers:

I have a bit of a love/hate thing with emacs. I love emacs ORG mode and it's got tons of great features and extensions. But the I find it difficult to remember all of the default keybinds. And some of the keybinds are just physically painful.

I have a few problems with my hands. So I tend to use vim, because it's a lot easier on my hands. There are some vim keybinds available for emacs - via evil mode and spacemacs - but I found evil mode only offers partial vi support, so it still requires a certain amount of emacs gymnastics to do certain things. And spacemacs has better vim-style support, but the spacemacs system is just too large, slow and bloated.
Compared to vim, and plain emacs - spacemacs takes ages to load.
If my hands were in a better condition, I'd probably use emacs a bit more often.
 
Last edited:
I think you're getting a bit confused.
In this context, you don't want to be messing with RAM Cache's or clearing system buffers, or messing with swap space. You're dealing with buffers in emacs. A completely separate topic.

In emacs, where it talks about buffers - it's talking about the buffer for the file.
This should clear up any confusion:

And regarding clearing a buffer:

And removing buffers:

I have a bit of a love/hate thing with emacs. I love emacs ORG mode and it's got tons of great features and extensions. But the I find it difficult to remember all of the default keybinds. And some of the keybinds are just physically painful.

I have a few problems with my hands. So I tend to use vim, because it's a lot easier on my hands. There are some vim keybinds available for emacs - via evil mode and spacemacs - but I found evil mode only offers partial vi support, so it still requires a certain amount of emacs gymnastics to do certain things. And spacemacs has better vim-style support, but the spacemacs system is just too large, slow and bloated.
Compared to vim, and plain emacs - spacemacs takes ages to load.
If my hands were in a better condition, I'd probably use emacs a bit more often.

I may be a little bit confused, but i came to the conclusion that there must be some buffer problem (emacs overall does seem to give programmers more control over this aspect) not necessarily because of emacs.
I've been learning javascript after having completed the sections on "Web Coding & Development" for dummies, and I practiced making one of those typical user-input programs for beginners. In emacs, i started typing what was literally in the books and practicing the keystrokes (clearly with another document opened that I saved myself because there's no way to remember all that unless you're a genius I guess...), but then i was having a problem: i was trying to play around with the "back a word" keystroke (Alt + b), and the cursor was dragging the entire line back the length of a tab...

That part of the story doesn't really matter, as i was messing with emacs again and the Alt + b function worked the way it was supposed to, so i was probably hitting the wrong buttons due to sleep deprivation and lots of coffee. Anyways...the reason I concluded that that the buffer had been altered is, i closed the file without saving and was like "i'm just going back to gedit, it's very simple and allows for copy and paste, plus i have the arrow buttons and home/end key which does the same thing as many of those emacs commands", then when i made my javascript program (i got a little creative and had a different user input), i clicked on the file to make it run in the browser, and i'm getting an alert box that says "What is your age?" My jaw dropped: Nowhere, in ANY part of the HTML file, were the words "what is my age?". The js syntax was also correct to the t....AND to figure out where this came from, i switched to my folder with all the programming files and typed "gedit *", and still i couldn't find that line of text.

Rebooting the computer and typing the code again made the program work, I realized an hour after that experiment that "What is your age?" was the text sample from the java program in the book that i was typing out when emacs opened, so i think yes it must be buffer related, maybe i accidently clicked "save buffer" or something like that when closing emacs.

Even though I know that such a conclusion would be overly dramatic (unless i had been clicking on a bunch of malware or something, or installing it through the terminal!) I was starting to think "Have hackers taken control over my firefox browser?! Are they trying to tell me that I'm immature for learning programming?! How hypocritical of them!" lmfao...
 
I may be a little bit confused, but i came to the conclusion that there must be some buffer problem (emacs overall does seem to give programmers more control over this aspect) not necessarily because of emacs.
I've been learning javascript after having completed the sections on "Web Coding & Development" for dummies, and I practiced making one of those typical user-input programs for beginners. In emacs, i started typing what was literally in the books and practicing the keystrokes (clearly with another document opened that I saved myself because there's no way to remember all that unless you're a genius I guess...), but then i was having a problem: i was trying to play around with the "back a word" keystroke (Alt + b), and the cursor was dragging the entire line back the length of a tab...

That part of the story doesn't really matter, as i was messing with emacs again and the Alt + b function worked the way it was supposed to, so i was probably hitting the wrong buttons due to sleep deprivation and lots of coffee. Anyways...the reason I concluded that that the buffer had been altered is, i closed the file without saving and was like "i'm just going back to gedit, it's very simple and allows for copy and paste, plus i have the arrow buttons and home/end key which does the same thing as many of those emacs commands", then when i made my javascript program (i got a little creative and had a different user input), i clicked on the file to make it run in the browser, and i'm getting an alert box that says "What is your age?" My jaw dropped: Nowhere, in ANY part of the HTML file, were the words "what is my age?". The js syntax was also correct to the t....AND to figure out where this came from, i switched to my folder with all the programming files and typed "gedit *", and still i couldn't find that line of text.

Rebooting the computer and typing the code again made the program work, I realized an hour after that experiment that "What is your age?" was the text sample from the java program in the book that i was typing out when emacs opened, so i think yes it must be buffer related, maybe i accidently clicked "save buffer" or something like that when closing emacs.

Even though I know that such a conclusion would be overly dramatic (unless i had been clicking on a bunch of malware or something, or installing it through the terminal!) I was starting to think "Have hackers taken control over my firefox browser?! Are they trying to tell me that I'm immature for learning programming?! How hypocritical of them!" lmfao...
Sounds like some text you had copied/killed into the kill ring, or the copy/paste buffer perhaps? or maybe you accidentally pasted some text before saving the file and quitting. IDK.

I'd say it's almost certainly some kind of user error. I've never had any weird problems with any text editors on any platform.

But emacs does get confusing sometimes. I've ended up trying to do things in emacs and got confused, or accidentally used the wrong set of keybinds and ended up doing something completely unintended to my file. That's happened a lot!

I used to have similar problems from time to time when I first started using vim. But the more you use editors like vim and emacs - the more you get used to their ways of doing things. I keep trying to use vim keybinds everywhere nowadays.

Several years ago, I set up a custom keybind in vim, whereby if I hit the j key twice in a row e.g. jj - it switches out of edit mode and back into command mode as if I've pressed <esc>. I know a few vim users who have re-mapped their <tab> key to <esc> and have mapped <esc> to <tab> - but that just seems crazy to me. As a programmer, I tend to use tabs a lot, so wouldn't want to have to keep reaching for the <esc> key to get a tab. And other vim users who have switched <esc> and <Caps lock>. Anyway, I discovered that other vim users were using this 'jj' keybind to quickly exit edit mode, instead of having to reach for the escape key or using ctrl + [ (which is another default vim keybind which is an alternative to using <esc>). So I tried it. And it's great - it's very effective. Only a crappy programmer would ever try to name variables jj - so there's no reason that I'd ever need to type jj in any kind of document. So using the jj keybind to trigger an <esc> and get out of edit mode is just brilliant.

But it's a double edged sword, because nowadays - whenever I'm typing in ANY text editor - even the editor for posts here on Linux.org - whenever I make some kind of typo, I automatically hit jj - expecting it to go into command mode, so I can quickly move to the place where the mistake is and fix it! I am SO used to vim's modal editing paradigm, that I expect it everywhere! Ha ha! I'll be typing in a non-vim text editor, like if I'm writing an email for work in Outlook. And I will notice I've made a typo three words back and then will be automatically typing nonsense like jj3bcefixed-wordjjA as if I'm in vim..... Then I realise I'm not and I'm thinking "Great! Now I still have the original typo to fix and I've added even more gibberish to my email!"

And having to reach for the arrow keys to move around in other text editors just infuriates me nowadays.
I'm so used to just hitting jj to switch to command mode and then using h,j,k,l, or using motion operators like w,W,E,e,B,b,f,F to quickly get jump to the mistake and fix it.

Hell, I even paid money for a vim plugin for Visual Studio at work, because NOT being able to use vim keybinds was driving me crazy! At one point, I was using Vim in Cygwin for editing source code and running builds via scripts in cygwin. The only times I even opened Visual studio were when I was debugging. Since getting the vim plugin - I'm spending a lot more time in Visual Studio,with my beloved jj keybind, of course! Ha ha!
 
I recently came across a video on youtube showing how to use “DOOM emacs” it looks really cool, it is themed from the old classic video game doom. I was blown away by how much emacs can actually do it had built in web browser , email. I read a funny comment left on youtube saying emacs should get rid of linux and have its own kernel lol
 
Sounds like some text you had copied/killed into the kill ring, or the copy/paste buffer perhaps? or maybe you accidentally pasted some text before saving the file and quitting. IDK.

I'd say it's almost certainly some kind of user error. I've never had any weird problems with any text editors on any platform.

But emacs does get confusing sometimes. I've ended up trying to do things in emacs and got confused, or accidentally used the wrong set of keybinds and ended up doing something completely unintended to my file. That's happened a lot!

I used to have similar problems from time to time when I first started using vim. But the more you use editors like vim and emacs - the more you get used to their ways of doing things. I keep trying to use vim keybinds everywhere nowadays.

Several years ago, I set up a custom keybind in vim, whereby if I hit the j key twice in a row e.g. jj - it switches out of edit mode and back into command mode as if I've pressed <esc>. I know a few vim users who have re-mapped their <tab> key to <esc> and have mapped <esc> to <tab> - but that just seems crazy to me. As a programmer, I tend to use tabs a lot, so wouldn't want to have to keep reaching for the <esc> key to get a tab. And other vim users who have switched <esc> and <Caps lock>. Anyway, I discovered that other vim users were using this 'jj' keybind to quickly exit edit mode, instead of having to reach for the escape key or using ctrl + [ (which is another default vim keybind which is an alternative to using <esc>). So I tried it. And it's great - it's very effective. Only a crappy programmer would ever try to name variables jj - so there's no reason that I'd ever need to type jj in any kind of document. So using the jj keybind to trigger an <esc> and get out of edit mode is just brilliant.

But it's a double edged sword, because nowadays - whenever I'm typing in ANY text editor - even the editor for posts here on Linux.org - whenever I make some kind of typo, I automatically hit jj - expecting it to go into command mode, so I can quickly move to the place where the mistake is and fix it! I am SO used to vim's modal editing paradigm, that I expect it everywhere! Ha ha! I'll be typing in a non-vim text editor, like if I'm writing an email for work in Outlook. And I will notice I've made a typo three words back and then will be automatically typing nonsense like jj3bcefixed-wordjjA as if I'm in vim..... Then I realise I'm not and I'm thinking "Great! Now I still have the original typo to fix and I've added even more gibberish to my email!"

And having to reach for the arrow keys to move around in other text editors just infuriates me nowadays.
I'm so used to just hitting jj to switch to command mode and then using h,j,k,l, or using motion operators like w,W,E,e,B,b,f,F to quickly get jump to the mistake and fix it.

Hell, I even paid money for a vim plugin for Visual Studio at work, because NOT being able to use vim keybinds was driving me crazy! At one point, I was using Vim in Cygwin for editing source code and running builds via scripts in cygwin. The only times I even opened Visual studio were when I was debugging. Since getting the vim plugin - I'm spending a lot more time in Visual Studio,with my beloved jj keybind, of course! Ha ha!
Lol, when i was learning emacs during those trying times i was worried i would become like that, but i think it's fine, and emacs is a great even though difficult text editor.

For now, I'm sticking with gedit because i sprained my finger while carrying my dead dog for burial, it does help to be flexible.
 
I'm sticking with gedit

Depending on your needs, you may find you can get by with just 'nano'. I'm a pretty big fan of nano. For what I do, it's pretty much perfect. It's pretty basic - but I don't do anything taxing. If I'm writing/editing code for a site or something, I'll use a more robust text editor.
 
Depending on your needs, you may find you can get by with just 'nano'. I'm a pretty big fan of nano. For what I do, it's pretty much perfect. It's pretty basic - but I don't do anything taxing. If I'm writing/editing code for a site or something, I'll use a more robust text editor.
I love nano and leafpad i use it all the time, i also dont do heavy programming but even if i was writing code in python i might use Sublime. To me theyre all the same the only difference is often key bindings for different features, depending which text editor you get used to you develope a muscle memory for the key bindings and tend to stuck with those habbits! i like nano because its easy and in most linux distros so its always there for you, but if people like to write code i can see why they might go for a more lavish option like emacs, sublime or vim or whatever
 
I love nano and leafpad i use it all the time, i also dont do heavy programming but even if i was writing code in python i might use Sublime. To me theyre all the same the only difference is often key bindings for different features, depending which text editor you get used to you develope a muscle memory for the key bindings and tend to stuck with those habbits! i like nano because its easy and in most linux distros so its always there for you, but if people like to write code i can see why they might go for a more lavish option like emacs, sublime or vim or whatever

hence...why i'm sticking with gedit because i can just copy/paste text to make things happen more quickly, can you do that with the GUI verion of VIM? You can do it with emacs but overall i don't want to mess with it since i have a busted finger.
 
hence...why i'm sticking with gedit because i can just copy/paste text to make things happen more quickly, can you do that with the GUI verion of VIM? You can do it with emacs but overall i don't want to mess with it since i have a busted finger.

This works pretty good for home desktops. But for servers with no GUI installed, you have to do everything
with nano, vi, or emacs. :)
 


Top