0

I have just started learning unix and came across very basic doubt in command line arguments.

Suppose if in my script i do:

echo $@ #Now this prints all the command line arguments

args=$@ #Args array will take the command line argument array from $@

echo $args 

Here i have doubt in last statement. echo arrayname as it should print only first index element but why is it showing the complete array?

If i take a normal array in unix and say array name is ARR,now if i use echo ARR,it will show me first element and not all elements.So why the behaviour is different with args above?

  • If args is an actual array (Jesse_b's answer), then $args is equivalent to ${args[0]} -- I can't tell you why, some historical quirk probably. – glenn jackman Apr 14 '18 at 0:36
0

It's printing every element because you have set a variable and not an array. To set an array you would need to do:

args=($@)
  • ok.But i i try to access this variable as an array and use echo ${args[0]},then it is able to read the first index.How is this possible? – rahul sharma Apr 13 '18 at 19:01
  • @rahulsharma: I cannot reproduce what you describe. – Jesse_b Apr 13 '18 at 19:02
  • See here pastebin.com/HGbUVm7C .The second and third line gives me same output if i call my script with 3 arguments.Is this normal behaviour? – rahul sharma Apr 13 '18 at 19:10
  • @rahulsharma: I'm not sure what you are showing me but args = $@ is a syntax error. No output is shown either. – Jesse_b Apr 13 '18 at 19:11
1

$@ behaves differently from an ordinary array variable without index because $@ has an "integrated index": It always means "all elements".

set -- a b c
echo $@
    a b c
set -x
var=$@
    + var='a b c'
ar=(a b c)
    + ar=(a b c)
echo $ar
    + echo a
    a

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.