-1

I have the follow files in my folder:

a.jpg b.jpg c.jpg

And I have the follow script:

#!/bin/bash
echo $1

If I run:

script.sh $(ls)

My output is:

a.jpg

But I want to be:

a.jpg b.jpg c.jpg

So, Why doesn't echo prints all the output from ls?

Magenta
  • 11
  • 4
  • 3
    (1) Are you sure you run `script.sh "$(ls)"`, not `script.sh $(ls)`? (2) Is this an exercise just to see how Bash behaves? If not then just run `ls` because [what you're doing is unnecessarily complicated](https://superuser.com/q/1352850/432690). – Kamil Maciorowski Aug 09 '23 at 14:59
  • (1) Yes you're right, I forgot the quotes, sorry. (2) Yes, is an exercise, I'm trying to understand how works spaces and new lines in bash, that's confusing for me. – Magenta Aug 09 '23 at 20:49
  • 1
    Replace `$1` with `$@`? – Cyrus Aug 09 '23 at 23:10

1 Answers1

1

In your script, you explicitly ask to echo only the first argument:

echo $1

If you would ask for the second argument

echo $2

you'd get b.jpg as output.

You can get all the files using echo $* or echo "$@".

Another option is that you make sure that the complete output of ls is packed in the first argument. You can do that by adding quotes around it.

script.sh "$(ls)"
roaima
  • 2,889
  • 1
  • 13
  • 27
Ljm Dullaart
  • 2,416
  • 8
  • 17