Click to See Complete Forum and Search --> : Writing my first complex bash script


KarrottoP
01-19-2005, 12:02 PM
I have written some cheesy bash scripts but nothing that involved variables and functions and all that stuff. What I am trying to acomplish is a bit more interesting (and I do have a bash book on the way).

I need this to save the output of the program faxstat to a file
#faxstat > /faxstatfile

then to evaluate the length of the file
#wc -c /faxstatfile

then run an if statement something like
"if the output of 'wc -c /faxstatfile' = "75 /faxstatfile' then "echo 'yes' " else exit.

This is simplified to what the function would be but I figured it would be a good way to get information on the functions I am trying to create here is my code that does not work:

#!/bin/bash
faxstat > /statfile
statsize ()
{
wc -c /statfile
}

if statsize = "75 /statfile"
then
{
echo "yes"
}
fi




Any help would be appreciated I am making a newbie out of myself with this bash scripting stuff.

Thanks.

mrBen
01-19-2005, 12:17 PM
Because you are putting a / at the beginning of your filename, it is trying to save it in the root (/) directory, which you are unlikely to have permissions for.

Either take it away completely, which will leave it in the directory you are currently in, or change it to ~/, which refers to your home directory.

davisfactor
01-19-2005, 02:27 PM
OK here you go:

First, let's create a file with 75 characters

davis@davis:[~/bin]: x=1; while [ $x -le 75 ]; do echo -n a >> /home/davis/faxstatfile; x=$((x+1)); done

davis@davis:[~/bin]: wc -c /home/davis/faxstatfile
75 /home/davis/faxstatfile


Now, my script will check the word count of this file and will respond with "yes" or "no" depending on the size of the file

davis@davis:[~/bin]: cat justlinux.sh
#!/bin/bash

#faxstat > /home/davis/faxstatfile

statsize=$(wc -c /home/davis/faxstatfile | awk '{print $1}')

if [ $statsize = 75 ]
then
echo "yes the word count is 75"
else
echo "no the word count is not 75"
fi


And this is what we get:

davis@davis:[~/bin]: sh justlinux.sh
yes the word count is 75


Let me know if you have any questions.

KarrottoP
01-19-2005, 02:52 PM
Thanks guys,
what davisfactor had written explains to me the syntax of what I am trying to better..... and mrBen I do have root and the script will be run from cron as root on a machine with a dedicated function so I chose the / directory just because it was convenient for testing purposes.

bwkaz
01-19-2005, 07:48 PM
Just one minor nitpick:

Originally posted by davisfactor
if [ $statsize = 75 ] You would want to use -eq there, not =.

In bash, = and == do string comparison. -eq does numeric comparison. The difference comes in if $statsize is 075 for some reason -- both = and == will fail the comparison, while -eq will succeed. So change this to:

if [ $statsize -eq 75 ] and all will be well. ;)

davisfactor
01-19-2005, 08:14 PM
Thanks bwkaz. I wasn't aware of any differences between -eq and = or ==.

:)