简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM