0

I am messing around with shell scripts and I am trying to get my script to take input from another command, like say ls. It is called like this:

ls | ./example.sh

I try to access the input from within example.sh

#!/bin/bash
echo $1

but it echoes back nothing. Is there another way to reference parameters given to bash by other commands, because it works if I type in:

./example.sh poo

2 Answers 2

1

Parameters and input aren't the same thing:

$ ls
example.sh  foo
$
$ cat example.sh
for param; do
    printf 'argument 1: "%s"\n' "$param"
done

while IFS= read -t 1 -r input; do
    printf 'input line: "%s"\n' "$input"
done
$
$ ls | ./example.sh
input line: "example.sh"
input line: "foo"
$
$ ls | ./example.sh bar
argument 1: "bar"
input line: "example.sh"
input line: "foo"
$
$ ./example.sh $(ls)
argument 1: "example.sh"
argument 1: "foo"

Parameters are the arguments passed to the script to start it running, input is what the script reads while it's running.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use xargs to do that.

ls | xargs ./example.sh

Resource

https://ss64.com/bash/xargs.html

https://www.cyberciti.biz/faq/linux-unix-bsd-xargs-construct-argument-lists-utility/

Or read man page for it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.