How to write a Bash shell script - by example

About writing shell scripts and making the most of your shell
Forum rules
Topics in this forum are automatically closed 6 months after creation.
Habitual

How to write a Bash shell script - by example

Post by Habitual »

Every Bash shell script needs 2 basic things to do it's work on its own. The shebang (or hashbang) and the executable file attribute.
Since EVERY shell script needs these 2 attributes, it might be a good idea to have a script that can do those 2 things for you.

What this script does is adds the shebang (#!/bin/bash) into a file and makes the file executable (700).
This script will help you code other scripts.

Code: Select all

#!/bin/bash
# Purpose:	Inserts #!/bin/bash into a file and makes it executable
# Usage: 	scriptname /path/to/file.sh
# Author: 	JJ/Habitual
# Date: 	Tue Jul 19, 2011
# Version: 	1311133977
# Disclaimer:	Use it, abuse it, just don't lose it.
MINPARAMS=1

if [ -n "$1" ]
then
echo "#!/bin/bash" > $1
chmod 700 "$1"
echo File $1 is now an executable and ready to be edited.
fi 

if [ $# -lt "$MINPARAMS" ]
then
  echo Usage: `pwd`/`basename $0` /path/to/script.sh
fi  
exit 0
Save it where ever you like.

Code: Select all

chmod 700 /path/to/saved/script.sh
Then run it, it will let you know what you need to do to use it.

Enjoy! Now let's code something!!!
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 3 times in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
richyrich

Re: How to write a Bash shell script - by example

Post by richyrich »

+1 vote to make this a bash sticky.

- hey new bashers, a keeper, a must have ! read it, figure it out, understand it ! . . li'l nuggets inside . . :mrgreen:

regards, richy
SimonTS

Re: How to write a Bash shell script - by example

Post by SimonTS »

Thanks for that Habitual. Looks simple enough - but doesn't mean I'd have a hope in hell of creating it myself from scratch :shock:

I've got to try and put some time aside to sit down and learn some of this stuff.
Habitual

Re: How to write a Bash shell script - by example

Post by Habitual »

SimonTS:

You can do it.
PM me if you get in a pinch.

Today or Tomorrow I'll explore functions (),
Oh Boy!

I'm no programmer either, ya know, but I have an avid affection for writing shell scripts. I live for the "A-Ha!" moment when something I crafted/created works.
I am an input junkie that needs visual and immediate feedback during the course of my daily work.
That and I hate typing (after 17 years of it).
Last edited by Habitual on Tue Jan 24, 2017 8:53 am, edited 1 time in total.
Reason: s/a avid/an avid/
User avatar
Pilosopong Tasyo
Level 6
Level 6
Posts: 1432
Joined: Mon Jun 22, 2009 3:26 am
Location: Philippines

Re: How to write a Bash shell script - by example

Post by Pilosopong Tasyo »

Another way to accomplish this sans the script-to-create-a-script (ok, that sounded recursively redundant...) is to use the Templates folder to store a boilerplate script. Create a text file, put the shebang line and whatever other code fragment/comment lines/etc. that you want to put, save the file -- e.g. filename = "Shell Script" -- in the ~/Templates folder and apply the execute bit.

Here's a sample boilerplate I use:

/home/administrator/Templates/Shell Script

Code: Select all

#!/bin/sh

##########
#
# Project     :
# Started     :
# Author      :
# Module      :
# Description :
#
##########

# start of code here

# EOF
When you want to create a new script, fire up the file browser, right-click an empty place on the right pane > Create a Document > Shell Script. Rename, open in the text editor, and start coding.

Applies to Gnome.
Last edited by Pilosopong Tasyo on Thu Jul 21, 2011 9:41 am, edited 1 time in total.
o Give a man a fish and he will eat for a day. Teach him how to fish and he will eat for a lifetime!
o If an issue has been fixed, please edit your first post and add the word [SOLVED].
Habitual

Re: How to write a Bash shell script - by example

Post by Habitual »

Pilosopong Tasyo:

Clever alternative! I like that. :wink:
beer-in-box

Re: How to write a Bash shell script - by example

Post by beer-in-box »

Please delete this post if this is not the place to ask and let me know so that I can ask the question properly :)

Is BASH a programming language itself or is it based on something and not a complete language?

EDIT: I am trying to learn Java, and this was supposed to be a hobby, but Java proved to be more than I thought, so I want to know what I am dealing with if I start to try to learn this :)
Habitual

Re: How to write a Bash shell script - by example

Post by Habitual »

Bash is not a "programming" "language" in that it does not have an interpreter.
Bash is a command processor.

https://secure.wikimedia.org/wikipedia/ ... d_language and
https://secure.wikimedia.org/wikipedia/ ... gain_shell

HTH,
Habitual

Re: How to write a Bash shell script - by example

Post by Habitual »

Habitual wrote:... in that it does not have an interpreter.
or compiler. :)
cfaj

Re: How to write a Bash shell script - by example

Post by cfaj »

Habitual wrote:Bash is not a "programming" "language" in that it does not have an interpreter.
Bash is a command processor.
Bash is an interpreter (that's how it executes scripts).
It is a programming language; "script" and "program" are synonymous.
Babbleshack

Re: How to write a Bash shell script - by example

Post by Babbleshack »

:P
excellent, I made the script include the extra comments.
great bit of code thanks much! :mrgreen:

Code: Select all

NOW=$(date +"%Y-%m-%d")


if [ -n "$1" ]
then
	echo "#!/bin/bash 
# Purpose: 
# Usage: 
# Author: Babbleshack
# Date: ${NOW}
# Version: 
# Disclaimer: " > $1
	chmod 700 "$1" 
	echo FILE $1 is now an executable and ready to be edited
fi
-Babble
Habitual

Re: How to write a Bash shell script - by example

Post by Habitual »

Of course, if you're into the shell as much as I am, you could use this in your ~/.vimrc

Code: Select all

au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent !chmod 700 <afile>
Any file.{ext} that has any shebang (perl, python, bash, whatever) will be made 700 upon exiting vi[m].

Enjoy.
tadaensylvermane
Level 2
Level 2
Posts: 88
Joined: Tue Jun 25, 2013 8:50 pm

Re: How to write a Bash shell script - by example

Post by tadaensylvermane »

This script is the total lazy mode. I love it!!! Never occured to me to do something like this before.
Habitual

Re: How to write a Bash shell script - by example

Post by Habitual »

tadaensylvermane wrote:This script is the total lazy mode. I love it!!! Never occured to me to do something like this before.
"Avoiding Repetitive Tasks" is the hallmark of any good systems administrator.

If you have to type it more than 3 times, write a script/alias/function.
Tim_Olaguna

Re: How to write a Bash shell script - by example

Post by Tim_Olaguna »

Habitual wrote:Of course, if you're into the shell as much as I am, you could use this in your ~/.vimrc

Code: Select all

au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent !chmod 700 <afile>
Any file.{ext} that has any shebang (perl, python, bash, whatever) will be made 700 upon exiting vi[m].

Enjoy.
Hum... I tried creating a /.vimrc file with the specified code [I copied and pasted the one entire line into a new text file created with 'pluma']. But upon trying to use 'vi' to create a new executable file I immediately received a message to the effect that coding was not use-able in the current bash environment. I am running Linux Mint 17.1. Do you have any thoughts as to why I might be getting such a message and how it might be mitigated?

Thank you in advance for your time and wisdom.
Habitual

Re: How to write a Bash shell script - by example

Post by Habitual »

Tim_Olaguna wrote:Hum... I tried creating a /.vimrc file with the specified code [I copied and pasted the one entire line into a new text file created with 'pluma']. But upon trying to use 'vi' to create a new executable file I immediately received a message to the effect that coding was not use-able in the current bash environment. I am running Linux Mint 17.1. Do you have any thoughts as to why I might be getting such a message and how it might be mitigated?
Tim:
Sure, if you create a ~/.vimrc file and you are certain that you have

Code: Select all

au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent !chmod 700 <afile>
then next time, try this:

vim x.sh # and the first line has to have a

Code: Select all

#!/bin/bash
# for .vimrc to work, this script has to have a shebang, be it bash, perl, python...

See this vidclip for an actual walk through.
tolkien

Re: How to write a Bash shell script - by example

Post by tolkien »

You can also give your script as an input to the bash interpreter:
bash /path/to/script
This way you don't need the shebang line and also not the chmod permission.
Works for other interpreter languages too, such as perl and python.
User avatar
xenopeek
Level 25
Level 25
Posts: 29507
Joined: Wed Jul 06, 2011 3:58 am

Re: How to write a Bash shell script - by example

Post by xenopeek »

Here's how I do it. In your home directory you'll find the subdirectory called Templates. Files that you put here will become available in your file manager's Create New Document submenu that you find in the File menu and in the context menu (right-click). So create a file in the Templates directory called "Bash" for example, put the shebang line and any other default lines you want in there, and change its permissions to be executable. Now any time you need a new bash file you can select it from the Create New Document menu.

You can organize your templates in subdirectories. I have a subdirectory called Scripts where I have a template for Bash and for Python for example.
Image
User avatar
Fred Barclay
Level 12
Level 12
Posts: 4185
Joined: Sat Sep 13, 2014 11:12 am
Location: USA primarily

Re: How to write a Bash shell script - by example

Post by Fred Barclay »

Hi xeno. Great idea! Just one incredibly minor question.
Is it necessary to change the permissions of the templates to executable? None of mine are, and they show up just fine under "Create New Document."

Code: Select all

fred@aussie! ~/Templates $ ls -al
total 24
drwxr-xr-x  2 fred fred 4096 Dec 20 12:23 .
drwxr-xr-x 62 fred fred 4096 Dec 20 02:15 ..
-rw-r--r--  1 fred fred   65 Dec 20 12:16 bash.sh
-rw-r--r--  1 fred fred   54 Dec 20 12:22 c.c
-rw-r--r--  1 fred fred   77 Dec 20 12:18 python2.py
-rw-r--r--  1 fred fred   76 Dec 20 12:19 python3.py
Thanks to Habitual for starting this and to the others too! :)
Image
"Once you can accept the universe as matter expanding into nothing that is something, wearing stripes with plaid comes easy."
- Albert Einstein
User avatar
xenopeek
Level 25
Level 25
Posts: 29507
Joined: Wed Jul 06, 2011 3:58 am

Re: How to write a Bash shell script - by example

Post by xenopeek »

If you change script files templates to executable, the script files created with "create new document" will be executable as well. Saves you having to change permissions on each newly created script file.
Image
Locked

Return to “Scripts & Bash”