$ cdExecuting the script
$ mkdir bin
$ cd bin
$ cat > script1
date
<Ctrl>d
Why are we getting this error message?
$ ./script1
bash: ./script1: Permission denied
We are still getting an error but this one is different!
$ ls -l script1
-rw-r--r-- 1 pattyo
sysadmin 5 Nov 11 08:13 script1
Ah, success!
$ chmod +x script1
-rwxr-xr-x 1 pattyo
sysadmin 5 Nov 11 08:13 script1
Success again!
To test our theory add the following line to your shell script
$ echo "echo $$" >> script1
Check the PID of your current shell
$ echo $$
1981
Now execute it like this
$ . script1
Mon Nov 11 08:32:49 PST 2002
1981
Type i to switch to vi's insert mode
Type in these lines:echo users currently logged in:
who | awk '{print $1}' | grep $1Press Esc to switch to vi's command mode
Type :wq and press Enter to save the file and exit viFix the permissions so it will execute.
$ chmod 755 checkuserNow execute your script.
$ ./checkuser your-login-name
Arithmetic opertors
| plus | + |
| minus | - |
| multiply | * |
| divide | / |
| remainder | % |
$ count=3
$ count=$count+1
$ echo $count
3+1
So how can numeric values be evaluated?
$ let x=3
$ let y=2
$ let z=1
$ let total=x+y+z
$ echo $total
6
The basic syntax is:use conditions to test values of variable, existence of files, status of command execution
if condition then
statements
elif condition then
statements
else
statements
fi
| > | greater than |
| >= | greater than or equal |
| < | less than |
| <= | less than or equal |
| == | equal |
| != | not equal |
Korn shell syntax
| Condition | string operator | arithmetic operator |
| greater than | > | -gt |
| greater than or equal | >= | -ge |
| less than | < | -lt |
| less than or equal | <= | -le |
| equal | == | -eq |
| not equal | != | -ne |
Bash shell syntax
if [ "$NAME" == "Jon Doe"
]; then
echo
$NAME
fi
$ bash testModify the script by removing the double quotes around $NAME
Jon Doe
$ bash test
test.bash: [: too many arguments
$ date | cut -c 12-13
14
#! /bin/ksh
hour=$(date | cut -c 12-13)
if (( hour <= 18
))
then
print
Good day, Patty
else
print
Good evening, Patty
fi
$ chmod +x hello
$ ./hello
Good day, Patty
if [ `date | cut -c 12-13`
-le 18 ];
then
echo
Good day, Patty
else
echo
Good evening, Patty
fi
#! /bin/bash
if who | grep $1 > /dev/null
then
echo $1 is logged in
else
echo $1 is not logged in
fi
$ ./who root
root is not logged in
echo -n "What is your favorite
operating system? "
read OS_NAME
# translate input to lower
case
# get rid of text after
a space
OS=`echo $OS_NAME | tr '[A-Z]' '[a-z]' | sed 's/ .*$//'`
if [ "$OS" == "unix" ]
then
echo
"Glad you like Unix, you will like Linux too."
elif [ "$OS" == "windows"
]
then
echo
"I guess you haven't tried a real operating system!"
else
echo
"You should give Linux a try!"
fi
Press Esc to swich to vi's command mode
Type :wq and press Enter to save and exit
vi
Make the program executable chmod +x os_choice
Execute the program:
$ ./os_choice
while conditionuntil is very similar. Typically while is the better choice.
do
statement
...
done
until conditionfor loop Example:
do
statement
...
done
for USERS in mike patty kelly
tom jill ed
do
echo
$USERS
done
Save the file and exit the editor
i=1
USERS="mike patty kelly
tom jill ed"
for i in $USERS; do
echo
"Hello there $i"
done
!/bin/shRunning a script in debugging mode# Begin by initializing the two variables
# sleep and sheep to 0.
# Don't confuse the function sleep (which will
# pause execution for a given number of seconds,
# with the variable sleep. sleep=0
sheep=0# As long as sleep is equal to 0 the
# while loop will not exit
# '-eq' is used for testing numbers
# '=' is used for testing strings, in this case
# the variable must be quoted
# Note how the Bourne shell handles arithmetic expressionswhile [ $sleep -eq 0 ]
do
let sheep=sheep+1
echo $sheep
doneCan you predict what will happen?
- Since the value of sleep is never changed, the loop will never exit and will go on indefinitely until you kill it!
- As an exercise put an exit clause in this shell script by modifying it somehow.
- (Hint: There are several ways to modify the script. You want to be sure to add and exit statement.)
sleep=0
sheep=0
while [ $sleep -eq 0 ]
do
let sheep=sheep+1
if [ $sheep -eq 100 ]
then
sleep=1
fi
echo $sheep
doneTest operators
- The choice of operator depends on whether you are testing numbers or strings.
- If you attempt to test a string with a numerical operator your script will not behave as you expected.
string = pattern string matches pattern (can contain wildcards) string != pattern string does not match pattern stringA < stringB stringA comes before stringB in dictionary order stringA > stringB stringA comes after stringB in dictionary order exprA -eq exprB Arithmetic expressions are equal exprA -ne exprB Arithmetic expressions are not equal exprA -lt exprB exprA is less than exprB exprA -gt exprB exprA is greater than exprB exprA -le exprB exprA is less than or equal to exprB exprA -ge exprB exprA is greater than or equal to exprB
$ sh -x myprog
$ bash -x myprog
Or add this line to your shell program right after the #!/bin/sh: set -x
In debug mode, the output will look confusing because the shell will do the following: It will print a plus (+) infront of each command being processed.
- read each line and process the line
- display the results of its processing of the command line
- execute the specified commands
The basic syntax is:
case expression in
pattern1 )
statements
;;
pattern2 )
statements
;;
...
esac
Code example:
#!/bin/sh leave=no while [ $leave = no ]; do cat << END MAIN MENU 1) Print current working directory 2) List all files in current directory 3) Print today's date and time x) Exit Please enter your selection $LOGNAME: END read selection case $selection in 1) pwd ;; 2) ls -l ;; 3) date ;; x) leave=yes ;; esac done exit 0
$ read line
All work and no play makes Jack a dull boy.
$ echo $line
All work and no play makes Jack a dull boy.
$ read stuff < /etc/passwd
$ echo $stuff
root:x:0:0:root:/root:/bin/bash
Your company just purchased another company and you have been tasked with the job of creating a user account for all the employees from the new company. Fortunately, you know how to write shell scripts!
The HR department has handed you a list of the new employees in the form of Lastname, Firstname. Write a program that creates new accounts for users based on this text file of names.
The user account names should be composed of their first initial followed by their last name. Truncate all account names to eight characters. The program should take input from the file of names provided by HR. You can use some of the code from the read example above. Your program should put all the new users in the group users.
Sample input file:
Example accounts generated from this file:Doe, John Smith, Candy Notingham, Michael
The useradd command can be used to create the accounts. Remember to place all users in the users group and to truncate all account names to 8 characters. This assignment is the class project for this semester. In order to get full credit, all criteria must be met. The program must work. Turn in both a paper and floppy copy of your final script. You can program in either the bash, sh, or ksh shell.jdoe csmith mnotingh
Hints:
You can use awk or cut to extract single characters or groups of characters from a string.
l=`echo $last | awk '{print substr($0,1,7)}'`Translate can be used to translate all characters to lowercase
l=`echo $last | cut -c 1-7`
These expressions will grab just the first character in a string and place it in the varible f:
f=`echo $first | cut -c 1-1`
f=`echo $first | awk '{print substr($0,1,1)}'`
$ echo "My Life iS BusY" | tr '[A-Z]' '[a-z]'
my life is busy