help with a bash script problem


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting help with a bash script problem
# 1  
Old 04-13-2011
help with a bash script problem

hi to everyone Smilie

i am new to linux and bash and i am trying to build a bash script, that is quite similar to the well known cmd 'split' ... Smilie
it is now already "working" ... i can use it like:
./splitfix.sh -v -s 10 foo
./splitfix.sh -s 10 -v foo
./splitfix.sh -s 10 foo
./splitfix.sh -v foo

when i try wrong params i dont get an error (or the shorthelp) function and i dont know how to implement the --verbose tag in my code Smilie

this is the third version of my script and i cant find a possibility to check the parameters.
i always have the problem, that if one parameter is -s that than has to follow a number (size in bytes or lines).

can anybody help me out? Smilie


Code:
#!/bin/bash
#simple Tool to split files and txt files
#02.04.2011


###########################################
function usage () {

cat << EOF
       $0 [OPTIONS] FILE [FILE ...] Split FILE into
       fixed-size pieces.
       The pieces are 10 lines long,
          if FILE is a text file.
       The pieces are 10 kiB long, 
          if FILE is *not* a text file.
       The last piece may be smaller, it contains the rest
          of the original file.
       The output files bear the name of the input file
          with a 4-digit numerical suffix.
       The original file can be reconstructed with
          the command   ``cat FILE.*´´
       
    EXAMPLE:
       splitfix.sh foo.pdf
         splits foo.pdf into the files
         foo.pdf.0000 foo.pdf.0001 etc.
         
    splitfix.sh [-h | --help] This help text
    splitfix.sh --version     Print version number
    
    OPTIONS:
    -h
      --help    this help text
    -s SIZE     size of the pieces
                  in lines (for text files)
                  or in bytes (for other files)
        -v
           --verbose print debugging messages
          
EOF

}


###########################################
function shorthelp () {

    cat << EOF
    Usage: splitfix.sh [OPTIONS] FILE [FILE ...]
    »splitfix-sh --help« for more information.
EOF

}


###########################################
function check_param () {

if [[ $1 == '-s' ]]
then
    printf "%d" $2 > /dev/null 2>&1
    if [[ $? == 1 ]]
    then
        shorthelp
        exit 1
    else
        SIZE=$2
    fi

    if [[ $3 == '-v' ]]
    then
        shift 3
        verbose=on
        splitting $SIZE $verbose $*
    else 
        shift 2
        echo "debug2"
        splitting $SIZE $*
    fi
else
    if [[ $1 == '-v' ]]
    then
        shift 1
        verbose=on
        if [[ $1 == '-s' ]]
        then
            printf "%d" $2 > /dev/null 2>&1
            if [[ $? == 1 ]]
            then
                shorthelp
                exit 1
            else
                SIZE=$2
                shift 2
                splitting $SIZE $verbose $*
            fi
        else
            splitting $verbose $*
        fi
    fi
fi

}

################################################
function splitting () {

    if [[ $SIZE != "" ]]
    then
        shift 1
    fi

    if [[ $verbose == "on"  ]]
    then
        shift 1
    fi

    for i in $*
    do
        # Existiert die Datei?
        if [[ -e $i ]]
        then
            file --mime-type $i | grep -iq text
            if [ $? -eq 0 ]
            then
                if [[ $SIZE -gt 0 ]]
                then
                    if [[ $verbose = "on" ]]
                    then
                        echo "Die Textdatei wird gesplited"
                    fi
                    split --suffix-length=4 -d --lines=$SIZE $i $i.
                else
                    if [[ $verbose = "on" ]]
                    then
                        echo "Die Textdatei wird gesplited"
                    fi
                    split --suffix-length=4 -d --lines=10 $i $i.
                fi
            else
                if [[ $SIZE -gt 0 ]]
                then
                    if [[ $verbose = "on" ]]
                    then
                        echo "Die Binärdatei wird gesplited"
                    fi
                    split --suffix-length=4 -d --bytes=$SIZE $i $i.
                else
                    if [[ $verbose = "on" ]]
                    then
                        echo "Die Binärdatei wird gesplited"
                    fi
                    split --suffix-length=4 -d --bytes=10000 $i $i.
                fi

            fi
        else
            echo "File $i does not exist."
            exit 1
        fi
    done
}


###########################################
# main()
case "$1" in
    '--help' | '-h')
        usage
    ;;
    *)
        # Mindestens ein Argument..
        if [ $# -gt 0 ]
        then
            check_param $*
            exit 0
        else
            shorthelp
            exit 1
        fi
esac

# 2  
Old 04-13-2011
# 3  
Old 04-14-2011
hehe nice hint, thx Smilie
saved a lot of my code Smilie

but one question i cant figure out yet ... how can i parse --verbose or --help with getopts??
i appended a sample code, how can i now build in --help and --verbose in getopts?! Smilie

Code:
#!/bin/bash
function usage(){
cat << EOF
    $0 [OPTIONS] usage
EOF
}

function shorthelp() {
    cat << EOF
    Usage: spltifix.sh [OPTIONS] FILE [FILE ...]
    splitfix.sh --help for more information
EOF

}

counter="0"
while getopts "hs:v" options; do
    case $options in
        h ) usage
            exit 0
            ;;
        s ) size=$OPTARG
            ((counter+=2))
            ;;
        v ) verbose='on'
            ((counter+=1))
            ;;
        \? ) shorthelp
             exit 1;;
    esac
done
echo $verbose
echo $counter
echo $size
shift $counter
echo $1
echo $2

# 4  
Old 04-14-2011
Quote:
Originally Posted by drjodo
but one question i cant figured out yet ... how can i parse --verbose or --help with getopts??
That's unfortunately quite simple to answer: You can't. You could perhaps just do [ "$1" == "--help" ] && stuff before you even run getopts, but things like --verbose that you'd expect to put in the middle of getopts' options? getopts would throw up on it.

Last edited by Corona688; 04-14-2011 at 07:12 PM..
# 5  
Old 04-15-2011
hmm that suxx Smilie
what can i do if i want to offer those options?
-v
-s SIZE
-h
--help
-v
--verbose
a for loop that checks for --verbose and --help and sets flag or prints help?!
and then launch getops? i think that will give an error, because the --verbose or --help is still in the arguments list?

any idea? Smilie

---------- Post updated at 05:27 PM ---------- Previous update was at 05:13 PM ----------

is there maybe a similar tool like getopts that can handle these types of parameters?
or does anybody have an idea, how i can build that script ...?

---------- Post updated 04-15-11 at 11:07 AM ---------- Previous update was 04-14-11 at 05:27 PM ----------

ok i now have it working Smilie
maybe some1 has an idea, how i can grab not existing parameters.
i thought i could use the if not exists clause and in the else tree i call shorthelp.

Code:
#!/bin/bash
#Just a little Script to split other files
#AE
#MS
#
#BS Praktikum SS 2011


###########################
# Print long help version #
###########################
function usage() {

cat << EOF

    $0 [OPTIONS] FILE [FILE ...] Split FILE into
        fixed-size pieces.
        The pieces are 10 lines long,
            if FILE is a text file.
        The pieces are 10 kiB long,
                if FILE is *not* a text file.
        The last piece may be smaller, it contains the rest
            of the original file.
        The output files bear the name of the input file
            with a 4-digit numerical suffix.
        The original file can be reconstructed with
            the command    ‘‘cat FILE.*''
    EXAMPLE:
        splitfix.sh foo.pdf
              splits foo.pdf into the files
             foo.pdf.0000 foo.pdf.0001 etc.
             
    splitfix.sh [-h | --help] This help text
    splitfix.sh --version   Print version number
    OPTIONS:
    -h
      --help    this help text
      -s SIZE     size of the pieces
                  in lines (for text files)
                   or in bytes (for other files)
    -v
      --verbose print debugging messages
EOF
}
############################
# print help short version #
############################
function shorthelp() {
cat << EOF
    Usage: splitfix.sh [OPTIONS] FILE [FILE ...]
    »splitfix-sh --help« for more information.            .
EOF
}

###############
# Versioninfo #
###############
function version() {
    echo "splitfix.sh ver0.8b"
}

########
# Main #
########

sizeFlag=0
size=10

function getSize() {
sizeFlag=1
}

if [[ $# -eq 0  ]]
then shorthelp
fi

#for (( i=1; $i <= $#; i++ ))
for i in $*
do
echo "i: $i"
echo "param count: $#"
echo "loop: $i"
echo "sizeFlag: $sizeFlag"

    if [[ sizeFlag -eq 1  ]]
    then 
        size=$1
        sizeFlag=0
        echo "size set"
    else
        case $1 in
            '-h' | '--help')
                usage
                exit 0;;
            '-s')
                echo "-s set"
                getSize;;
            '-v' | '--verbose')
                verbose=on;;
            '--version')
                version
                exit 0;;
            *)
            echo "no more params, file?"
            
            
            if [[ -e $1  ]]
            then
                file --mime-type $1 | grep -iq text
                if [[ $? -eq 0 ]]
                then
                    if [[ $verbose == "on"  ]]
                    then
                        echo "File $1 is a textdocument"    
                        echo "Now splitting the file ..."
                        split --verbose --suffix-length=4 -d --lines=$size $1 $1.
                    else
                        split --suffix-length=4 -d --lines=$size $1 $1.
                    fi
                else
                    if [[ $verbose == "on"  ]]    
                    then
                        echo "File is a binary/other document"
                        echo "Now splitting the file ..."
                        split --verbose --suffix-length=4 -d --bytes=$size"k" $1 $1.
                    else
                        split --suffix-length=4 -d --bytes=$size"k" $1 $1.
                    fi
                fi
            else
                echo "File $1 does not exist."
                exit 1
            fi
        esac    
    fi
    shift 1
    echo "shifting"
done
exit 0

# 6  
Old 04-20-2011
One last question ...

I cant figure out the main difference between:
if [[ expression ]]; then
if [ expression ]; then
if expression; then
if(expression); then

sometimes it works without the [[ braces, and if i put the expression in [[ it doesnt work any longer Smilie


halp plox Smilie
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

Array problem in Bash Script

I am trying to write a Bash Script using a couple of arrays. I need to perform a countdown of sorts on an array done once daily, but each day would start with the numbers from the previous day. This is what I'm starting with : #!/bin/bash days=(9 8 7 6 5) for (( i = 0 ; i < ${#days} ; i++... (4 Replies)
Discussion started by: cogiz
4 Replies

2. Shell Programming and Scripting

Bash/awk script problem

Hi, I have 100 files containing different values in single column, I want to split those files in two separate files (file2 and file3) based on average value of first column of each file, for those files I am working on the following script #bin/bash for memb in $(seq 1 100) do awk... (4 Replies)
Discussion started by: dsp80
4 Replies

3. Shell Programming and Scripting

Help with bash script problem

Hi, Below is my bash script: cat run_all.sh if && ; then Number_Count_Program $1.results $2.results > $1.$2.counts else Number_Split_Program $1.results $2.results > $1.$2.split fi After I run the following command: ./run_all.sh A B ./run_all.sh: line 1: Anybody advice to edit... (5 Replies)
Discussion started by: perl_beginner
5 Replies

4. Shell Programming and Scripting

Problem with Bash Script.

Hi guys! I'm new to the forum and to the Bash coding scene. I have the following code paths=/test/a paths=/test/b keywords=\"*car*\" keywords=\"*food*\" for file in `find paths -type f -ctime -1 -name keywords -print 2>/dev/null` do #.... do stuff here for every $file found... (5 Replies)
Discussion started by: RedSpyder
5 Replies

5. Shell Programming and Scripting

Problem using grep in bash script

When it comes to programing and UNIX, I know just enough to be really really dangerous. I have written a python script to parse through a file that contains ~1 million lines. Depending on whether a certain string is matched, the line is copied into a particular file. For the sake of brevity,... (4 Replies)
Discussion started by: errcricket
4 Replies

6. Shell Programming and Scripting

problem using variables in bash script

I am using variable to give the location of the file I am using but I get error. Here is the code: LogFile=/tmp/log.email echo -e "could not close the service - error number $error \n" > $LogFile well this is not all the code but is enough because the problem start when I try to use the... (3 Replies)
Discussion started by: programAngel
3 Replies

7. Shell Programming and Scripting

Simple bash script problem

#!/bin/bash cd /media/disk-2 Running ./run.sh it's not changing directory.Why? (6 Replies)
Discussion started by: cola
6 Replies

8. Shell Programming and Scripting

Problem in bash script

I have written a script and I get error and I don't understand why. neededParameters=2 numOfParameters=0 correctNum=0 while getopts "s:l:" opt do case "$opt" in s) serviceName= $OPTARG #errorline 1 numOfParameters= $numOfParameters + 1 ;; l) ... (12 Replies)
Discussion started by: programAngel
12 Replies

9. UNIX for Dummies Questions & Answers

Bash script argument problem

I'm having problems with bash scripts. If a bash script is called with no arguments, I always get "PHIST=!" as the first argument (i.e. this is what $1 equals). Why? Where does this come from, and how can I fix it? Nothing in the bash man pages refer to this mysterious default argument. (2 Replies)
Discussion started by: sszd
2 Replies

10. Shell Programming and Scripting

bash script problem

hi I am writing a bash script that uses dialog to get user input an diplay messages to user. I have a small problem dialog --inputbox "blabla" 20 50 2> /tmp/output VAR="'cat /tmp/output'" mkdir $VAR the code below requests user for a directory path to be created. But, if the user uses... (1 Reply)
Discussion started by: fnoyan
1 Replies
Login or Register to Ask a Question