- 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
do
echo $i
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
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 "Please type your name"
read name
echo "Hi $name, lets be friends!"