Shell scripts is a really useful skill to have. Creating a script to do avoid repeating a task can save you time in the long run. What a lot of people don’t know is that shell scripting is not hard, especially if you have some Linux command line experience. You can pretty much do anything you want with a script, and they are great for automating tasks. To create a shell script from a one-liner all you really have to do is:
echo "[your one-liner here]" > [your-script-name-here]
That will create your file, which you can then change the permissions on and move to your ~/bin/ directory. It would be wise to add $!/bin/bash as the first line if bash is your shell of choice, if you choose to distribute it. Once you’ve translated your one-liner into a file that can be executed you can start adding functionality to the script to ease use for future use.
Here are some explanations of basic functionality you can add to your scripts:
If-then-else statements If then else’s can be used to control flow or make decisions, they are very useful indeed.
read can be used to get input from the user, when dealing with an unknown or a variable
functions are great to use to store a particular set of instructions that can be called repeatedly without having to re-write the script.
loops do exactly as it sounds, loop. That is re-iterate over a variable, or repeat an instruction. You could use a loop to call a function over and over until a clause is met.
getopt’s is an instruction that can be used to read input from when the script is called. Often this is used to change functionality or display usage information.
redirection techniques are used throughout shell scripts and is one of the fundamentals of shell scripting. Master this and you’ll be piping and redirecting output to files and other programs in no time.
error checking and handling, often overlooked but shouldn’t be underestimated. Checking for errors before they happen can save time, and undesired results.
Many of these techniques are covered throughout this blog (feel free to browse or search), and there are many great online resources and books available (both free and paid) to help you with your journey. A good place to start for most of the techniques is in my Shell Scripting 101 article. Good luck!