Muzy Muzy - 3 years ago 192
Linux Question

how to get the next input command based on the previous command comparison [bash-script]

my code is something like this

#!/bin/bash
for i in $1 $2 $3 $4; do
if [[("$i" == '-f')]] ; then #I'm searching if the user input the -f switch
if [ -f "$((i+1))" ]; then # I'm trying to increment the position of $i to get the input that follows the -f switch and check the existence of the file
echo "$((i+1)) file found"
else
echo "$((i+!)) file not found"
fi
fi
done


my question is how to get the input from the user after a specific input which is in my case -f. is this possible to do in bash scripting.
any hint on how to do. thanks.

Answer Source

You should almost certainly use getopts, but you could just set a flag while iterating:

#!/bin/bash

unset FLAG
for x; do
        if test -n "$FLAG"; then
                FILENAME=$x
                unset FLAG
                continue
        fi
        case $x in
        -f) FLAG=1;;  # Set flag for next iteration
        *) echo "processing argument $x"
        esac
done
echo "FILENAME=$FILENAME"

This is terribly fragile, and I feel somewhat guilty suggesting it. Really, use getopts instead of trying to roll your own argument parsing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download