In Linux I tend to create my own scripts to try to automate the most stuff possible. In order to do so I used to create a new file in /usr/local/bin
, make it executable and then start writing script into that file :
touch /usr/local/bin/my-script
chmod +x /usr/local/bin/my-script
vim /usr/local/bin/my-script
when vim opens I tend to start my scripts with something like this :
#!/bin/bash
echo hello
I mainly set the interpreter to /bin/bash so I would have to add the whole shebang stuff each time on the first line.
Automate the automation
To avoid these steps I created a new script that I called localScript
:
#!/bin/bash
if [[ -z $1 ]]; then
echo "You need to set the name of the script you want to edit/create"
exit 0
fi
SCRIPT_PATH="/usr/local/bin/${1}"
INTERPRETER=bash
if [[ ! -f $SCRIPT_PATH ]]; then
if [[ ! -z $2 ]]; then
INTERPRETER=$2
fi
echo "#!/usr/bin/env $INTERPRETER" > $SCRIPT_PATH
/bin/chmod +x $SCRIPT_PATH
fi
/usr/bin/vim $SCRIPT_PATH
First off I want to make sure the user enters an argument when calling this command. If he does not he will receive a message and the script will stop.
Then I set 2 variables, SCRIPT_PATH
and INTERPRETER
The first one is to define the path in which to create my script file and is based on the first argument when the command is called. The second one is the interpreter I will define in the shebang
of my script.
If the file does not exist I want to create a new file and insert the first line with the correct interpreter on the first line and then make it executable.
I will then edit the file with Vim.
The result :
β ~ localScript bash-script
// Vim opens the script, when I close wim without adding anything :
β ~ cat /usr/local/bin/bash-script
#!/bin/bash
β ~ localScript python-script python3
β ~ cat /usr/local/bin/python-script
#!/usr/bin/env python3
This will make creating and editing custom commands a little faster and a little easier :)
Dennis de Best
Comments