Home > other >  How to read specific named argument in bash script
How to read specific named argument in bash script

Time:12-08

Currently I'm executing my bash script with unnamed filename parameters:

./exec.sh filename1 filename2 

What I want to achieve is to add one named parameter s

./exec.sh filename1 filename2 -s bla 

where s is an optional argument stands for "suffix" and if exists, has to be appended to all filenames inside script.

I have a part in bash script that looks like:

for param in "$@"
do
    file_name=$(< $files/$param)

As far as I know, I should use getopt but not sure about its syntax.

How can I implement to get optional -s parameter from the arguments list?

CodePudding user response:

I agree with @Fravadona, using getopts may be the best choice, but try this as an individual logic workaround.

_Note: By this, you are able to set the '-s <YOUR_SUFFIX_PATH>' anywhere in the command line.

#!/bin/bash

# Your first option variable to catch.
_opt1='-s'

# Indexing variable you don't need to modify.
_n=0

# Create an array from all arguments.
_inputs=( `echo $@` )

# After this for loop block you can call the argument assigned to -s by
# calling the "${_arg1}" variable (if found any).
for _i in "${_inputs[@]}" ;do
  if [ "${_i}" == "${_opt1}" ] ;then
    _opt1arg_index=$(( $_n 1 ))
    _arg1="${_inputs[$_opt1arg_index]}"
  fi
  _n=$(( _n 1 ))
done

# Note: If you need to pars the script arguments in your code use the 
# following 'while' block to avoid reading the '-s' and the argument assigned to it.
while [ ! "$*" == '' ] ;do
  if [ "${1}" == "${_opt1}" ] ;then
    shift 2
  fi

### Put your code from here...

  # example
  echo "${_arg1}/${1}"

### ... To here

  shift
done

Test by:

test-script.sh file1 file2 -s /usr/local file3 file4 

Output should be:

/usr/local/file1
/usr/local/file2
/usr/local/file3
/usr/local/file4

CodePudding user response:

example of custom parsing of arguments:

#!/bin/bash

__ARGV__=( "$@" )

for i in "${!__ARGV__[@]}"
do
    case ${__ARGV__[i]} in
    -s|--suffix)
        suffix=${__ARGV__[i 1]}
        unset __ARGV__[i] __ARGV__[i 1]
        ;;
    -s=*|--suffix=*)
        suffix=${__ARGV__[i]#*=}
        unset __ARGV__[i]
        ;;
    esac
done

# debug info
printf '%s\n' "${__ARGV__[@]/%/$suffix}"

Now, the command:

./exec.sh filename1 filename2 -s .bla filename3

outputs:

filename1.bla
filename2.bla
filename3.bla
  • Related