linux 1 min
Convert Bash Scripts Into Named CLI Commands in Linux
Save a long terminal command as a one-word command, better than copy-paste or digging through history.
When your daily OS is Linux, sometimes some terminal commands are so useful you might want to save them.
For example I had a weird monitor whose output mode was not detected automatically. I used xrandr to add a mode to set the proper resolution.
I used to copy-paste this command into the terminal.
xrandr --addmode VGA1 "1024x600_60.00"
It was usually in terminal history so sometimes I used to only hit the up arrow key to find that command.
However it is not ideal to do it like this because sometimes I pollute my terminal history with many trials or installing packages and need to find this mode string again.
Save complex command to single keyword
Maybe there is a simpler way but this is what I have found working for myself.
Open Terminal and paste:
cd /usr/local/sbin/ && sudo touch [your-command] && sudo chmod +x [your-command] && sudo gedit [your-command]
When the text editor opens with elevated permissions paste your command there as shown below and save:
#!/usr/bin/env bash
[your terminal command]
If for some reason your command does not work you can try wrapping your command in eval.
#!/usr/bin/env bash
eval "[your terminal command]"
End
Now you can use your-command in your terminal. Type the beginning of your command and press Tab to see if it’s recognized.
You see, we are typing your command multiple times; the process is quite painful, but better than copy-pasting or having to google it again IMHO.
Maybe we can write some command that generates these. Hit the comments if you have already written such a thing.