- Here's the mandatory first bash script:
#!/bin/bash
echo "Hello World"
- This one prints numbers from 1 to 4:
#!/bin/bash
for i in 1 2 3 4 5 6
do
echo $i
# note that the value of the variable has $ infront, and that
# the "#" sign denotes a comment EXCEPT if followed by a '!".
done
- If we omit the stuff including and after the "in" in a
for loop, bash takes it to mean that we want
the loop index to range over the command line arguments (given
when the command is invoked). For instance,
#!/bin/bash
for ut
do
mv $ut `echo $ut | tr "[a-z]" "[A-Z]"`
done
# The tr command translates letters, in our example from upper to lower case.
# Note the single quotes around the shell-interpetble command:
# Bash will execute the command inside ` ` and return the results.
# In other words, bash will first executes a shell command in ` ` and then
# copy the vlue of $ut to the reulting value (upper-case file name).
Here, ut is a variable that ranges over the arguments.
Lets put this shell script in a file called toupper and
invoke toupper as: toupper home.accounts office.accounts. Then, the loop variable ut essentially first takes the
value home.accounts, then takes the value
office.accounts. The above shell script renames each file
given as argument by replacing every lowecase letter with an
upper case letter.
An important point to note in the above command is
the backquote (`). This is a cue to bash
to execute the command enclosed within the backquotes
and return the
result. Without the backquotes, the above command will not
produce the desired effect.
You can even run the shell script on itself!; like so:
toupper toupper
From this point, you will have to refer to the script as
TOUPPER.
- The read command reads input from
the terminal. Try the following shell script
#!/bin/bash
echo "Type your name"
read name
# let's add some color to life! (next line sets the fonts)
echo -en "\033[1;36;44m"
# outputs the name:
echo "Hi, $name, let's be friends!"