0

I m trying to work some bash scripts on my own.

Let's say I'd like add "hi" at the beginning of lines such as;

a="find . -type f"

$ for i in $a;do echo hi $i; done

but output is:

hi find
hi .
hi -type
hi f

I'd like to put every beginning of variable execution as file output, which is here a, "hi" how can i do that?

EDIT: i want to add hi to very fron of "a" variables output, but this script adding hi every line of a..

EDIT: for type -f to -type f, thanks @Terrance

may output be;

hi ./me
hi ./you

sorry for unclear question i hope may edit work...

  • I don't really understand what you're talking about, but possibly you want to quote your variables for i in "$a"; do echo hi "$i"; done (the first is critical here, the second advisable) – Zanna Aug 3 '17 at 13:32
  • You have added hi inside the loop, so it will be printed everytime the loop is executed. write echo hi outside the loop. – luv.preet Aug 3 '17 at 13:33
  • 2
    please edit your question, and add the expected output. (i.e. how would you like to see the output of your script) – Yaron Aug 3 '17 at 13:36
1

Your for loop treats the $a as a string and will not execute it.

Use $(command) when you need to execute something inside another command.

So what you would do in your case is (please don't do that, but follow the hint below):

for i in $($a); do echo hi $i; done

Additional Hint: Avoid using a for loop with find output, as you will run into issues when your file names contain spaces.

In your case the following will work:

a="find . -type f"
while IFS= read -r i; do
    echo "hi $i"
done < <($a)

<(command) creates a temporary file of the command output.)

  • nowly, tried this; for i in $a;do echo hi $i; done , i got what i want but why do i need to put `` ? – solfish Aug 3 '17 at 13:46
  • `...` is more or less the "same" as $(...). But I did not write that... – pLumo Aug 3 '17 at 13:54

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.