A few days ago, we posted a few effective methods to effortlessly retrieve commands from Linux command history like a pro. Creating a script for a Linux command is one of them.
Using a script for a Linux command is like having a smart assistant. It saves you time because you don't have to type long commands over and over. You just run the script, and it does the work for you.
This way, you make fewer mistakes and get things done faster. Plus, you can share this script with others, so they can easily do the same thing.
In this brief tutorial, I will explain how to create a script for a command in Linux with an example.
Table of Contents
Create a Script for a Linux Command
Creating a script in Linux for your complex commands is quite simple! Here's a step-by-step instructions on how to create a script for your commands:
1. Choose a Text Editor:
You can use any text editor like nano
, vim
, or gedit
. For beginners, nano
is usually easier.
2. Create a New Script File:
Open the terminal. Type nano myscript.sh
(or replace nano
with your preferred editor and myscript.sh
with your desired file name).
3. Write the Shebang Line:
At the top of the file, write #!/bin/bash
. This line tells the system that the script should be run in the Bash shell.
4. Add Your Command:
Below the shebang line, type in your commands exactly as you would in the terminal. For example, I am going to add the following command:
cat ostechnix.txt | tr '|' '\n' | sort | tr '\n' '|' | sed "s/.$/\\n/g"
As you can see, the above command is bit longer and difficult to remember. For those wondering, this command takes a file where items are separated by pipes, sorts these items, and then outputs them as a single line separated by pipes, but removes the last pipe and ends the line properly with a newline character. For example, if the file ostechnix.txt
contains c|a|b
, the output after running this command would be a|b|c
.
If you have multiple commands, you can put them on separate lines, or use semicolons ;
to separate them on the same line.
You can also add comments by starting a line with #
. This won't be executed and is useful for notes or explanations.
5. Make the Script Executable:
Save the file and exit the text editor.
Run the following command to make your script executable:
$ chmod +x myscript.sh
6. Run the Script:
To run your script, use ./myscript.sh
from its directory.
$ ./myscript.sh
If it's located in a directory included in your PATH
(Eg. /usr/bin/
or whatever your PATH
is), you can just type myscript.sh
.
This method is generally effective for most needs. However, there are other ways to manage complex commands:
- Aliases: For shorter or frequently used commands, you can create aliases in your
~/.bashrc
or~/.bash_aliases
file. - Bash Functions: Bash functions in your
~/.bashrc
can be more flexible than aliases and are useful for slightly more complex tasks. - External Tools: For very complex tasks, especially those involving automation across systems, you might consider tools like Ansible, Chef, or Puppet.
Choosing between these options depends on the complexity of your tasks and your personal or organizational needs. For most individual use cases, a simple Bash script as outlined above is more than sufficient.
Quickly Create a Script with Last Executed Command
How do you create a script of the last executed command? It is easy! Remember we use "!!
" to repeat the last command? Hence, you can use the echo
command to append the last executed command into your script like below.
$ echo "!!" > script-name-here.sh
Please be careful while using "!!
". Double check your last command before running this.
Next open the script file and add the appropriate shebang (like /bin/bash
or /bin/sh
) at the start of the script. Save the file and close it.
Set executable permission to the script:
$ chmod +x script-name-here.sh
Now run the script using command:
$ ./script-name-here.sh
Why Shebang is Important in Scripts?
Adding a shebang at the start of a script is generally recommended for various reasons. Let us discuss a few important points.
The shebang (#!
) followed by the path to an interpreter (like /bin/bash
or /bin/sh
) is a crucial part of a well-written script. It ensures that the script is executed in the correct environment, regardless of which shell the user is currently in.
1. Why Include a Shebang?
The shebang line tells the system which interpreter to use to execute the script. Without it, the system might use a different shell or interpreter than the one you intended, which can lead to unexpected behavior or errors.
2. Choosing Between #!/bin/bash
and #!/bin/sh
:
#!/bin/bash
: Use this if your script relies on Bash-specific features or syntax. Bash has more features than the standard shell (sh
), like certain array operations or string manipulation techniques.#!/bin/sh
: This is for scripts that use only standard shell syntax, which is more portable across different Unix-like systems. However, on many systems (like Ubuntu),/bin/sh
is actually linked to/bin/dash
, which is a shell designed to be faster and more efficient than Bash, but with fewer features.
3. Which One to Choose?
If you are writing a script for personal use on a system where you know Bash is available (like most Linux distributions), using #!/bin/bash
is generally fine.
If you aim for portability or are writing scripts that should work on a wide range of Unix-like systems, including those where Bash might not be installed by default (like in some minimal Docker images), then #!/bin/sh
is a safer choice.
Including the shebang line is considered a best practice in script writing and is particularly important for ensuring that your script behaves consistently across different environments.
As a beginner, sticking to #!/bin/bash
for your personal scripts on Linux is a good choice, especially if you are going to use Bash-specific features.
What to do if the Interpreter is not installed in the default path?
If the interpreter you want to use for your script is not installed in the default path (like /bin/bash
or /bin/sh
), there are a few approaches you can take:
1. Use env
to find the Interpreter:
A more flexible approach is to use env
in the shebang line. This is useful because it allows the script to be more portable, as env
will locate the interpreter in the system's PATH
.
For example, if you're writing a Bash script and you want to use whatever Bash version is default for the user, you can use #!/usr/bin/env bash
.
This approach is particularly common in environments where the interpreter might be in different locations on different systems.
2. Specify the full Path to the Interpreter:
If you know the exact path to the interpreter, you can specify it in the shebang line. For example, if your Python interpreter is located at /usr/local/bin/python3
, you would start your script with #!/usr/local/bin/python3
.
3. Modify the PATH
Environment Variable:
If the interpreter is in a location that's not in your current PATH
, and you don't want to (or can't) specify the full path in every script, you can modify the PATH
environment variable to include the directory where the interpreter is located.
You can do this by adding a line like export PATH=$PATH:/path/to/interpreter-directory
in your .bashrc
, .bash_profile
, or .profile
file, depending on your system setup.
This way, you can just use #!/bin/bash
, #!/usr/bin/env python3
, etc., in your scripts.
4. Install the Interpreter in the Default Path:
Another solution, especially if you have administrative rights and you're setting up a system for consistent use, is to install the interpreter in one of the standard locations (like /usr/bin/
or /usr/local/bin/
).
This might involve either using a package manager to install the interpreter (which usually places it in a standard location) or creating a symbolic link from the actual location to a directory in your PATH
.
5. Error Handling in Scripts:
In some cases, you might want to add error handling in your script to check if the required interpreter or command is available. You can do this with simple checks within the script to see if commands exit with an error and then print an informative message.
Remember that the chosen approach should align with your specific needs and the constraints of your environment. For personal or development use, modifying your PATH
or using env
is often sufficient. For more controlled or production environments, ensuring that the interpreter is installed in a standard location is usually preferable.
Hope this helps.
1 comment
Newbie here… shouldn’t you add a shebang at the start of the script as a matter of good script writing? Maybe something like “#!/bin/bash” or is this unnecessary? Also, should it be “#!/bin/bash” or “#!/bin/sh”? Thanks!