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.
Note: If you don't have gedit, you can use any other text editor that comes with your distribution of Linux.
me@ubu:~$ mkdir scripts me@ubu:~$ cd scripts me@ubu:~/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.
Type these two lines, and then save the small file by clicking on the floppy disk icon.
#!/bin/bash echo "Hello World!"
Now run your script by typing:
me@ubu:~/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:
Didn't work, right? Actually there are two reasons it didn't work. Type this:
me@ubu:~/scripts$ echo $PATH me@ubu:~/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.
You should also see a line something like this:
-rw-rw-r-- 1 me me 32 Jun 29 11:28 myscript
Notice the first part of that line. There are 4 parts to it:
- The type of file (a regular file) rw- Permissions for the owner of this file 'me' rw- Permissions for the group 'me' r-- Permissions for others
For the permissions, the first is to read the file. The second (w) it to write to it (change it). The third is permission to eXecute (run) the script. The hyphen means nobody has that permission.
Well, we can easily fix the permissions, anyway.
me@ubu:~/scripts$ chmod +x myscript me@ubu:~/scripts$ ls -l me@ubu:~/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 and the slash to mean "look in this directory", and now it should now work without using sh first.
We can fix the second problem (at least temporarily) by adding this directory to the path:
me@ubu:~/scripts$ echo $PATH me@ubu:~/scripts$ export PATH=$PATH:~/scripts me@ubu:~/scripts$ echo $PATH me@ubu:~/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:
me@ubu:~/scripts$ alias ll='ls -l' me@ubu:~/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.
Printed from linux.bz (Shell Scripts - Linux.bz, Linux in Belize)