2014-08-18

Batch Scripting in Linux (Shebangs, Shebangs...)

GOAL: Write batch scripts in Linux and to automate repetitive tasks.

Note: Coming from a DOS (.bat) and Windows (.cmd) environment, writing batch files have always been a valuable skill to have.  It allows you to automate a lot of tasks that you would have to do manually when as a network admin, or as "security researcher"  So, how do you do batch files in Linux? 

Tools Used:
gedit (or any text editor you like)
terminal
file manager

In Linux, your DOS and Windows batch files are equivalent to shell scripts.  Unlike DOS and Windows, which is looking for a .bat or .cmd, Linux does not care as long as the file is set as executable.  You can create a script with any text editor (gedit).  On the first line, you'll have to declare the shell interpreter you want it to use - either bash - #!/bin/bash or sh - #!/bin/sh.  Save the file and set it to be executable.  Of course the command you type in sequence would have to have proper syntax and logic flow to work properly.... don't get stuck in a loop. 

You can either right-click and set the properties of the file through the gui interface or from the terminal type - chmod 755 (or +x) <filename>.

Execution:
1. You can double-click the file, and your file manager will ask if you want to run it 
--OR--
2. You can invoke the the script from the terminal by typing - ./<filename>

More Info: 

Script files

A shellscript usually resides inside a file. This file can be executable, but you can also call a Bash with that filename as parameter:
bash ./myfile
There is no need to add a boring filename extension like .bash or .sh. This is UNIX®, where executables are not tagged by the extension, but by permissions (filemode). Of course, you can name the file like you want! To add proper filename extensions is a convention, nothing else.
chmod +x ./myfile
If the file is executable (and you want to use it by just calling the script name), you need to specify the shebang!

The Shebang

The in-file specification of the interpreter of that file, like:
#!/bin/bash
echo "Hello world..."
This thing usually 1) is interpreted by the kernel of your system. In general, if a file is executable, but actually not an executable (binary) program, and such a line is present, the program specified after #! is started with the scriptname and all its arguments. These two characters # and ! have to be the first two bytes in the file!
You can follow it by using the echo program as fake-interpreter:
#!/bin/echo
We don't need a script-body here, as the file will never be interpreted and executed by "echo", but you can see what the system does, it calls "/bin/echo" with the name of the executable file and all what follows.
$ /home/bash/bin/test testword hello
/home/bash/bin/test testword hello
The same way, with #!/bin/bash the shell "/bin/bash" is called with the script-file as argument. It's exactly the same to execute "/bin/bash /home/bash/bin/test testword hello" here!