Bash script - how to read a file line by line when using getopts

I want to do two things in this script: 1) pass the file name to the script 2) pass the script parameters

Example 1: $./test_script.sh file_name_to_be_read pass only file names in a script

example 2: $./test_script.sh -a -b file_name_to_be_read enter the file name and parameters for the script

I can get example 1 to work using the following codes:

while read -r line ; do
    echo $line
done

In Example 2, I want to add additional flags like these:

while getopts "abc opt; do
    case "$opt" in
    a) a=1
       echo "a is enabled"
       ;;
    b) b=1
       echo "b is enabled"
       ;;
    esac
done

but how to do it so that the file_name is mandatory and be used with or without parameters?

+4
source share
1 answer

getopts (, -); . OPTIND , ; .

while getopts "ab" opt; do
    case "$opt" in
    a) a=1
       echo "a is enabled"
       ;;
    b) b=1
       echo "b is enabled"
       ;;
    esac
done

shift $((OPTIND - 1))

echo "$# arguments remaining"
for arg in "$@"; do
    echo "$arg"
done

, bash tmp.bash -a -b c d e,

$ bash tmp.bash -a -b c d e
a is enabled
b is enabled
3 arguments remaining:
c
d
e
+3

Source: https://habr.com/ru/post/1619981/


All Articles