0

I have a custom command that I create call PUSH

I want to run

PUSH #1 #2 #3 #4

I want to dynamically access all my arguments, I seem to have a hard time. How do I correctly do it?

I want to access

#1 #2 #3 #4

I know I can not use $1, $2, $3, or $4.

I've tried

PUSH a b c | echo $@

halfer
  • 19,824
  • 17
  • 99
  • 186
code-8
  • 54,650
  • 106
  • 352
  • 604

2 Answers2

0
$ cat args.sh
#!/bin/bash

echo ${@}

for a in "${@}"; do
    echo ${a}
done

$ bash args.sh foo bar baz
foo bar baz
foo
bar
baz

You're on the right track with $@. You can either access all the arguments at once (my first echo) or you can use a loop (my for) since I assume you'll eventually want to do something besides echo in the real script.

Stephen Newell
  • 7,330
  • 1
  • 24
  • 28
  • 1
    Always double-quote `"$@"`. – rici Mar 03 '18 at 19:57
  • To follow on to what rici said above -- when you say `for a in ${@}`, you get `./yourscript "argument one" "argument two"` printing `argument`, `one`, `argument`, `two` instead of `argument one` and `argument two`. The quotes really are critical. – Charles Duffy Mar 04 '18 at 15:47
  • Good catches, thanks. I do enough shell that I remember this *after* I get bit, but not enough that I think of it before. Answer has been updated. – Stephen Newell Mar 04 '18 at 17:14
0

I think you're doing the right thing, but the way that you're testing that syntax isn't right. $@ will give you access to the arguments passed into your script, but your command, PUSH #1 #2 #3 #4 | echo $2 has two problems. First of all, the first octothorpe is starting a line comment. you are running PUSH followed by the bash comment, #1 #2.... Second, in the scope of this command, $@ will reference the argument passed into this shell session, not the argument passed into the command before it. To test this syntax correctly, you need to use it in the script itself, like this:

- ❯❯❯ cat push.sh
#!/bin/bash

echo $@
- ❯❯❯ ./push.sh one two three
one two three

Or even more succinctly,

- ❯❯❯ bash -c 'echo $@' here are some args
are some args
Conrad.Dean
  • 4,341
  • 3
  • 32
  • 41