1

I know I can pass arguments to a bash function like

function output () {
  echo 'text' > text.txt;
  echo $1 >> text.txt;
  echo 'more text' >> text.txt;
}
output something;

But I actually need to pass the output of another script or program and have it in one variable, so I am able to call the function like

output $(ls);

... and have the output of ls in one single variable in the function. Is that possible? How?

Or can I at least echo every single input to the function?

1
  • You'll find a lot of help with bash on the superuser.com stackexchange. Commented Oct 29, 2013 at 21:07

3 Answers 3

2

Try quoting the arguments:

output "$(ls)";

or changing your function to

function output () {
  echo 'text' > text.txt;
  echo "$@" >> text.txt;
  echo 'more text' >> text.txt;
}
Sign up to request clarification or add additional context in comments.

Comments

0
#!/bin/bash 
output=`ls -larht` 
/bin/echo -e "$output"

1 Comment

Doesn't work the way I meant. :/ I want to pass this output to the function into one variable.
0

It is possible.

Consider this decimal to hex function, which takes the output of printf, and stores it in a var called NUM.

d2h()
{
  NUM=$(printf "%x\n" $1)
  echo $NUM
}

4 Comments

In bash, printf has this wonderful -v switch so that a=$(printf ...) is usually better written as printf -v a ... (think of C's sprintf). So that your d2h function would be more elegantly and more efficiently (think no subshells) written as d2h() { printf -v NUM '%x\n' $1; echo $NUM; }
that's legit. I'm impressed.
if you're not initializing a variable, it should be prepended with $. Are you putting printf $total ?
I was initializing one - the total seemed to be the output of ls.

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.