What is a bash script?
A bash script is an executable script that can be run from the command-line. It can then, in turn perform any other command-line commands. This way you can group commands and add logic around their order of execution, or pass variables to them and act upon those or pass them along to other scripts.
Creating a bash script:
To create a bash script you need to create a file with the extension ".sh".
$ nano script.sh
Now we need to add some functionality to our script, let's keep it simple at first:
clear pwd
Our command is not quite ready to be run yet, now we need to give the file 'execute' permission, we can do this by running the command:
$ chmod +x script.sh
When we run this command the screen will be cleared and the current working directory will be printed on the screen.
$ ./script.sh
That's it, your bash script is created and you are now able to use it.
Accessing variables
In your script you can access variables passed to it and make decisions based on those variables or pass them along to other scripts. Variables are passed as number in the order that they appear in the given command. Let's build a script that check's out a certain branch in git.
branch=$1 git checkout $branch
Let's execute our command and see that the branch is checked-out:
$ ./script.sh master
Master will now be the checked out branch if we are in a git repository.
Making it more accessible
Creating scripts can be really cool and can help you in automating processes easily, but typing out ./script.sh option option ... can become quite tedious, so let's take a lesson from the bash aliases tutorial and add an alias for our script.
alias sc='~/script.sh'
And now you can execute your script easily by running:
$ sc master
No comments:
Post a Comment