-1

How do I format in a script the number of arguments passed through a bash script? This what I have currently that works:

#!/bin/bash

echo "$# parameters"
echo "$@"

But I wanted to format is using a function but everytime I run it, it comes back as 0 parameters:

#!/bin/bash

example()
{
 echo "$# parameters"; echo "$@";
}

example

Am I thinking about this incorrectly?

David M
  • 1
  • 3

2 Answers2

1

You are not passing the arguments to your function.

#! /bin/bash

EXE=`basename $0`

fnA()
{
    echo "fnA() - $# args -> $@"
}

echo "$EXE - $# Arguments -> $@"
fnA "$@"
fnA five six

Output:

$ ./bash_args.sh one two three
bash_args.sh - 3 Arguments -> one two three
fnA() - 3 args -> one two three
fnA() - 2 args -> five six

It's the POSIX standard not to use the function keyword. It's supported in bash for ksh compatibility.

EDIT: Quoted "$@" as per Gordon's comment - This prevents reinterpretation of all special characters within the quoted string

Kingsley
  • 14,398
  • 5
  • 31
  • 53
0

The second one should work. Following are few similar examples I use every day that has the same functionality.

function dc() {
    docker-compose $@
}

function tf(){

  if [[ $1 == "up" ]]; then
    terraform get -update
  elif [[ $1 == "i" ]]; then
    terraform init
  else
    terraform $@
  fi
}

function notes(){
  if [ ! -z $1 ]; then
    if [[ $1 == "header" ]]; then
      printf "\n$(date)\n" >> ~/worknotes
    elif [[ $1 == "edit" ]]; then
      vim ~/worknotes
    elif [[ $1 == "add"  ]]; then
      echo "  • ${@:2}" >> ~/worknotes
    fi
  else
    less ~/worknotes
  fi
}

PS: OSX I need to declare function you may not need that on other OSes like Ubuntu

Prav
  • 2,785
  • 1
  • 21
  • 30
  • 3
    You should almost always double-quote variable references (e.g. `docker-compose "$@"` instead of `docker-compose $@`. This avoids unexpected behavior from spaces, wildcards, etc in the variables' values. – Gordon Davisson Nov 11 '18 at 22:19
  • @GordonDavisson That is true, but in some cases, it helps when Bash use spaces to create a multi-parameter effect especially for things like Terraform and Docker. But I get your point that almost always people only tend to use one parameter. – Prav Nov 11 '18 at 22:26
  • 1
    In those cases, it's almost always better to use an array (provided you're using bash, not something like dash that doesn't have them). Then use the array with the idiom `"${array[@]}"`, which'll treat each array element as a separate word but not get confused by spaces etc in the element values. – Gordon Davisson Nov 11 '18 at 22:51