0

I have a docker Entrypoint script that looks like this:

#!/bin/sh
LABEL=$1
mkdir -p /backup/$LABEL
...

I can access the arguments passed in the normal bash way via $1, $2, etc. but I also need to know the number of arguments passed in. At first I thought I could do this like this:

if [ $# -eq 2 ];
  then

However that does not work. Any ideas on how to retrieve the number of arguments?

TIA, Ole

Ole
  • 41,793
  • 59
  • 191
  • 359
  • How did you confirm `that does not work`? Please provide a [mcve]. – sjsam May 20 '16 at 03:30
  • This should work in normal cases. Be we don't have any idea about how parameters are passed to the script, what you pass, and what you get? – sjsam May 20 '16 at 03:38
  • I put an echo on $#. It is zero. To see for yourself just build a simple image and echo $#. Everything echoed from the Entrypoint script is reported on the console. – Ole May 20 '16 at 03:50
  • Please update the question with the above information. I haven't used docker so far so can't help myself with `just build a simple image and echo $#`. :( In a normal bash script, `echo #?` should give you the total number of parameters passed to the script.. – sjsam May 20 '16 at 04:20
  • `echo #?` returns blank for me even outside of the docker environment. `$#` does return the correct number of arguments outside the docker environment. I switched to using the following check for the third parameter instead of using the total number of parameters: `if [ -z "$RESTORE" ]`, so that gets me around the issue. Would still be nice to have an answer though. – Ole May 20 '16 at 13:50

2 Answers2

1

Weird. This should work. But, if you can read the positional parameters $1 and $2, you may have luck looping over them:

#!/bin/bash

params="$@"
while param=$1 && [ -n "$param" ]
do
    shift
    ((count += 1))
    echo "here comes $param"
done

echo "All params: ${params[@]}"
echo "We saw $count of them"
pneumatics
  • 2,836
  • 1
  • 27
  • 27
0

OK - In reality nothing passed in was resolving. The reason is that the entrypoint line needs to look like this:

ENTRYPOINT ["bash", "/run.sh"]

Mine looked like this:

ENTRYPOINT ["/run.sh"]

See here for more info: Referencing the first argument passed to the docker entrypoint?

Community
  • 1
  • 1
Ole
  • 41,793
  • 59
  • 191
  • 359