Example:
bash script.sh "hello world"
(in script echo "$1"
)
hello world
Question:
bash script.sh "good" "morning" "everybody"
What do I have to write in my script to output directly:
goodmorningeverybody
So, in general, I want $1
, $2
, $3
, ... (can be 100 but I don't know) to be saved in one variable for example VAR1
.
You can refer to all the positional arguments with $*
and $@
.
From 3.4.2 Special Parameters
*
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c…", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
@
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" …. If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).
So to get good morning everybody
as output you could just use echo "$*"
or echo "$@"
.
In general @
is the more useful of the two variables.
However, if you really want the worlds all smushed together the way you indicate then you have a few options.
The most straightforward of which is a simple loop:
for word; do
s+=$word
done
(for
without the in <list>
part operates on the positional arguments).
However, you can also do this with *
by controlling IFS
.
So you could also do s=$(IFS=; echo "$*")
. You want/need the sub-shell to avoid setting IFS
for the current shell.
Try doing this:
#!/bin/sh
var=$(printf '%s' "$@")
echo "$var"
or even better, credits to chepner :
printf -v var '%s' "$@"
or
#!/bin/bash
for arg; do
str+="$arg"
done
echo "$str"
Output :
goodmorningeverybody
Note :
"$@"
expands to each positional parameter as its own argument: "$1" "$2" "$3"...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With