2

So I tried making a function in a script that creates a new variable for each argument when running the script. This is my code:

#!/bin/bash

# Creating function log
#ARG1=${1}

log() {
  echo "You called DA LOG FUNCTION!!!1!!11one111!"
}

log

#echo "${1}"
#echo "$ARG1"

fcta() {
  for ((x=0;x<1000;++x)); do
   "a$x"=${1}
   if [[ ${#} -gt 1 ]]; then
     shift
   else
     x=1001
   fi
  echo "${a$x}"
#  echo "${1}"
}

fcta $@

I get this:

vagrant@localhost vagrant]$./luser-demo10.sh 12 12 12
You called DA LOG FUNCTION!!!1!!11one111!
./luser-demo10.sh: line 25: syntax error near unexpected token `}'
./luser-demo10.sh: line 25: `}'
[04:11----------------------------------------
vagrant@localhost vagrant]$

So this is line 25

#  echo "${1}"
} <----- LINE 25

fcta $@

EDIT: Thanks for telling me about the missing "done". People asked what I was trying to do, well I asked another question for that, since this one has been answered (question was, why did I get a syntax error). Thanks again.

iamAguest
  • 483

2 Answers2

4

In your function there is a do but no matching done to close the command list.

Try shellcheck to verify your scripts. This is a report of detected bugs and suspicious points in your script:

Line 16:
  for ((x=0;x<1000;++x)); do
  ^-- SC1009: The mentioned syntax error was in this for loop.
      ^-- SC1073: Couldn't parse this arithmetic for condition. Fix to allow more checks.
                          ^-- SC1061: Couldn't find 'done' for this 'do'.

Line 25:
}
^-- SC1062: Expected 'done' matching previously mentioned 'do'.
 ^-- SC1072: Unexpected keyword/token. Fix any mentioned problems and try again.
andcoz
  • 17,130
3

andcoz showed what was wrong in your code (a missing done to close the loop, for starters), but I think it looks as if you really want an array.

It's unclear what you want your code to do, but it looks like it's approximately equivalent to copying the command line arguments to an array:

a=( "$@" )

You can then get a particular element of that array with ${a[i]} if i is a variable with an integer value.

It's crucial to double-quote the expansion of $@ as this would quote the individual elements of the $@ list. Without the double quotes, the shell would split the elements on whitespaces (the contents of IFS), and filename generation ("globbing") would be performed on them.

Use break to exit a loop instead of setting the loop variable to a value past the end of the loop.

Kusalananda
  • 333,661