I need to form a single variable from a for loop.
My script:
#! /bin/sh
if [ "$#" -le 1 ]; then
echo "Illegal number of parameters"
exit 1
else
# Form domains variable
DOMAINS=""
for i in "${@:2}"; do
DOMAINS+="$i,"
done
echo "${DOMAINS::-1}"
fi
When I execute it:
sh script.sh command domain1 domain2
I get the following error:
certbot.sh: line 10: DOMAINS+=mmand,: not found
certbot.sh: line 10: DOMAINS+=domain1.com,: not found
certbot.sh: line 10: DOMAINS+=domain2.com,: not found
It seems as I used bash syntax since the following execution works:
bash script.sh command domain1.com domain2.com
I get:
domain1.com,domain2.com
I need it to work as sh not bash. I can't seem to find a solution.
+=
is not valid in a POSIX shell.
Since it is not a valid variable assignment,
DOMAINS+="$i,"
is interpreted as the name of a command, which is obtained by parameter expansion of i
. For instance, if i
equals 1, the line corresponds to
DOMAINS+=1,
If you had an executable file named DOMAINS+=1,
in your PATH, this file would be run.
You have to catenatate variables like this:
FOO=$FOO$BAR$BAZ
You can't avoid repeating the name FOO .
An alternative would be to switch to zsh or bash, where your usage of +=
would indeed have the desired effect.
Just:
IFS=,
echo "$*"
Or you seem to want from a second argument. Then like:
( shift; IFS=,; echo "$*" )
Did you try changing DOMAINS+="$i,"
into DOMAINS="${DOMAINS}${i},"
relying on variable substitution?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.