Reputation: 17
I'm trying to list script's argument by printf
function. Arguments are counted by iteration of $i
. What should be in printf
function?
I need something like
eval echo \$$i
but in printf
function.
Edit: Have while cycle with iteration of $i
and among other code, I have
printf "%s" $i
But, instead of $i
, I need some code, that shows me value of argument.
In my case, it is name of file, and I need list them. One file in one iteration.
Upvotes: 0
Views: 599
Reputation: 1973
It is not very clear what you are asking for, but this will list the arguments passed to the script:
while [ $# -gt 0 ]; do
printf "%s\n" "$1"
shift
done
Upvotes: 1
Reputation: 295679
To get your arguments in such a way that they can be fed back into the shell with the exact same value, the following bash extension can be used:
printf '%q ' "$@"; printf '\n'
This works even for rather unusual cases. Let's say that one of your arguments contains a newline:
./your-script 'hello
world' 'goodbye world'
This will be represented in the printf output:
$'hello\nworld' goodbye\ world
...with something you can use again in the shell:
$ echo $'hello\nworld' goodbye\ world
hello
world goodbye world
Upvotes: 0
Reputation: 69368
I guess what you are asking for is how to make the indirect reference to positional parameter i
(i containing the position):
print "%s\n" ${!i}
Upvotes: 0
Reputation: 754590
As noted in a comment, you normally do that with a loop such as:
i=1
for arg in "$@"
do
echo "$i: [$arg]"
((i++))
done
(If echo
isn't allowed, use printf "%s\n" …
where the …
is whatever would have followed echo
.)
You might also use indirect expansion to avoid the use of eval
:
for i in 1 2 3 4; do echo "$i: [${!i}]"; done
You can generalize that with:
for i in $(seq 1 $#); do echo "$i: [${!i}]"; done
or
for ((i = 1; i <= $#; i++)); do echo "$i: [${!i}]"; done
For example, given:
set -- a b 'c d' ' e f '
all the loops produce the output:
1: [a]
2: [b]
3: [c d]
4: [ e f ]
The square brackets are merely there to delimit the argument values; it allows you to see the trailing blanks on the fourth line of output.
You might also be able to use:
printf "[%s]\n" "$@"
to get:
[a]
[b]
[c d]
[ e f ]
Upvotes: 2