How do you create a script of a Linux command? So, you can simply run the script to get the output of a lengthy and complex command's output easily. I already follow a few methods to remember the Linux commands. We can recall the forgotten commands using the apropos command, or bookmark the frequently used commands, or save important commands in your Terminal, so we can use them on demand. There are N number of ways. However, knowing yet another method isn't bad - hence this post. If you're wondering how to create a script of Linux command, read on. It is not that difficult as you may think.
Create A Script Of A Linux Command
Let us say, we run the following command to alphabetically sort a file named ostechnix.txt and display the output in a single line:
$ cat ostechnix.txt | tr '|' '\n' | sort | tr '\n' '|' | sed "s/.$/\\n/g"
I don't know about you, but I have a terrible memory. No matter how many times I run this command a day, I will eventually forget it on the next day or the day after the next day. Sure, we can do a reverse search and bring up this command from the Bash history or follow any one of the methods given in the introductory section. But I'd love to learn other alternative methods too. This is why I decided to create a script of a Linux command. In this way, I can name the script as I wish and run it without having to whole command every time.
That's easy! Create a script.sh file and put your command inside it.
Or, you can do this as one-liner like below:
$ echo "your-command" > script-name.sh
And, then make the script executable. Done!
For example, I created a script of the above lengthy command like below.
$ echo "cat ostechnix.txt | tr '|' '\n' | sort | tr '\n' '|' | sed "s/.$/\\n/g"" > sortfiles.sh
Make the script executable:
$ chmod +x sortfiles.sh
Finally, run the following command to execute your Linux command:
Quite easy, right? You can choose an easy-to-remember name of your choice to the script. This is just an example. The use case might be different for you. Also, you can move the script to your PATH (Ex. /usr/bin/ or whatever your PATH is), so all users can use this without having to type the original path name.
How do you create a script of the last executed command? Yes, you guessed it right! Remember we use "!!" to repeat the last command? Hence, the command would be:
$ echo "!!" > script-name-here.sh
Please be careful while using "!!". Double check your last command before running this.