bash script
🗞Shell
bash
scripting
Steps to create a bash script executable and run it
- Create file with
.shextension, e.g. withtouch filename.sh - Write contents of your script (see below)
- Make it executable:
chmod +x filename.sh - Move file into folder
~/binor equivalently$HOME/bin -
Check whether the
~/binfolder is in your path and add it if necessary- I put my own shell scripts into the folder
~/bin. - To check whether the folder
~/binis in your system’sPATH, runecho $PATH. -
If you don’t see
~/binin there (e.g.something:~/bin:something-else) add it to the end of yourPATHviaexport PATH=$PATH:~/bin - Open a new shell tab so that the new
PATHis active. - You can now run the script executable with
$ filename
- I put my own shell scripts into the folder
-
Optional:
- Add
alias myScriptName='./filename.sh'to.bash_profile - Reload shell or run
. .bash_profile -
Call your new shell script by just typing
myScriptName
- Add
My first shell script - step by step
-
Write a program
- First line is
#!/bin/bash(bashshell) or#!/bin/sh(shshell) - Then write your code below, e.g.
#!/bin/bash # My first script echo "Hello World!" - First line is
- Save it as
my_script -
Setting permissions - in order to make the script executable
chmod 755 my_script -
Run the script
./my_script - Put script into the folder
/Users/myName/binto make it executable from anywhere because hopefully/Users/myName/binis already in the path.
Example and instructions taken and adapted from http://linuxcommand.org/wss0010.php
Recipe to write a basic shell script
Example 1
#!/bin/bash -l
export LANG=en_US.UTF-8-l: Use currently logged-in user
Example 2
This example contains an if-then clause.
# test if the current commit already has a tag
has_tag=$( git describe --tags --exact-match --match=builds/$PLATFORM/* HEAD || echo false )
if $FORCE || [ "$has_tag" == "false" ]
then
# proceed with build
exit 0
else
# nothing changed
exit 1
fiLinks
- See the Wikipedia article for more examples.
- How do I parse command line arguments in bash?
Discuss on Twitter ● Improve this article: Edit on GitHub