Editing Scripts

We will use the gedit editor to create what may be your first shell script. Type the above after you open the editor, like this, and then click on the Save button to save it. Click on the X in the upper right corner to close the window.

ubuntu@ubuntu:~$ mkdir scripts ubuntu@ubuntu:~$ cd scripts ubuntu@ubuntu:~/scripts$ gedit myscript

That will make a scripts directory, change into it, and launch the gedit with the filename myscript. Since it does not exist, gedit will create it.

Now run your script by typing:

ubuntu@ubuntu:~/scripts$ sh myscript Hello World!

This shows the classic programming course first program. It's just enough to see that the program actually did something. Now try it this way:

ubuntu@ubuntu:~/scripts$ myscript

Didn't work, right? Actually there are two reasons it didn't work. Type this:

ubuntu@ubuntu:~/scripts$ echo $PATH ubuntu@ubuntu:~/scripts$ ls -l

The $PATH variable contains a list of the directory paths (separated by colons) that bash will search to find an executable program, including a script. Your ~/scripts directory is not in there.

Also, notice that the x (executable) permission is not set, even for you, the script owner. Well, we can easily fix the second one.

ubuntu@ubuntu:~/scripts$ chmod +x myscript ubuntu@ubuntu:~/scripts$ ls -l ubuntu@ubuntu:~/scripts$ ./myscript

The first line uses the chmod command to add the executable flag for all users. The second line shows the change in permissions. In the third line, we added the dot to mean "look in this directory", and it should now work.

We can fix the second problem (at least temporarily) by adding this directory to the path:

ubuntu@ubuntu:~/scripts$ echo $PATH ubuntu@ubuntu:~/scripts$ export PATH=$PATH:~/scripts ubuntu@ubuntu:~/scripts$ echo $PATH ubuntu@ubuntu:~/scripts$ myscript

Now any scripts we make, we can run directly, if we add the execute flag using chmod.

While we're at it, we can create an alias so we don't have to keep typing ls -l:

ubuntu@ubuntu:~/scripts$ alias ll='ls -l' ubuntu@ubuntu:~/scripts$ ll

Now ll will give us a long listing. The change will be temporary, though; the alias will go away when we reboot. If you have an installed (not LiveCD) version of Linux, you could use gedit to edit the file .bashrc to add the alias line we just used.

This page is
made possible by:

This page rendered by CodeIgniter in 0.0372 seconds.