-1

Say, I have a command in bashrc alias which might require variable arguments/parameters. I was able to write it using if else as follows

yd(){
    if  (( $# )) && (( $1 == 1 ));
    then
    youtube-dl -f 18 "$2" &&  aplay /usr/share/sounds/ubuntu/stereo/message.ogg && notify-send 'Youtube Download Completed !'
    fi
    if  (( $# )) && (( $1 == 2 ));
    then
    youtube-dl -f "$2" "$3" &&  aplay /usr/share/sounds/ubuntu/stereo/message.ogg && notify-send 'Youtube Download Completed !'
    fi
}

Where 1st parameter represents the number of parameters I need. I want to know if there is a way to send variable number of parameters to the alias

  • Function definition is much _better_ and _readable_ when compared to a complex `alias` definition. Retain the function itself – Inian May 18 '17 at 13:10
  • That isn't valid code; you need to replace `else if` with `elif`, or add another `fi` to the end to end the outer `if` statement. – chepner May 18 '17 at 13:29

1 Answers1

1

You don't need to do anything special. There is no expected number of arguments to a shell function; you simply access what is given with $1, $2, etc. You can write the function as

yd () {
  if (( $# == 0 )); then
    printf 'Need at least 1 argument\n' >&2
    return 1
  fi

  arg1=18
  arg2=$1

  if (( $# > 1 )); then
    arg1=$1
    arg2=$2
  fi

  youtube-dl -f "$arg1" "$arg2" && 
    aplay /usr/share/sounds/ubuntu/stereo/message.ogg &&
    notify-send 'Youtube Download Completed !'
}

However, it might make more sense to reverse the order of the arguments to your function; then you can simply provide a default value of 18 for the second one if it isn't given.

# yd foo runs youtube-dl 18 foo
# yd foo 9 runs youtube-dl 9 foo
yd () {
    # Return 1 and print an error message if no first argument
    arg2=${1:?First argument required}
    # Use 18 if no second argument
    arg1=${2:-18}

    youtube-dl -f "$arg1" "$arg2" && 
      aplay /usr/share/sounds/ubuntu/stereo/message.ogg &&
      notify-send 'Youtube Download Completed !'
}

In either case, if yd is called with more than 2 arguments, who cares? yd simply ignores $3, $4, etc.

chepner
  • 497,756
  • 71
  • 530
  • 681