0

Please, don't be too much strict to my question and even it's a structure (maybe I have structured the sentence in a wrong way), as I am learning bash scripting. So the goal is to pass variable, which on his turn is another command (eg. ls -l | wc -l), to script execution. To pretend this is my command from my terminal

./variables.sh (ls -l | wc -l)

As you may guess, this doesn't work and throws an error

bash: syntax error near unexpected token `ls'

So the question is - how to do it right?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Norayr Ghukasyan
  • 1,298
  • 1
  • 14
  • 28
  • 1
    Put it in quotes, not parentheses – Barmar Sep 12 '19 at 20:30
  • 2
    so, if for example `ls -l | wc -l` returns the number 7, you want your script to execute as `./variables.sh 7`? If that is the case, all you need is `./variables.sh $(ls -l | wc -l)` although others will warn you that piping output of `ls` can cause hard to diagnose problems. Good luck. – shellter Sep 12 '19 at 20:30
  • that might depend on how "primary" script expect arguments, but check man of xargs – agg3l Sep 12 '19 at 20:30
  • Pass them in double quotes and run via `eval $*`. But it’s highly not recommended to do this way. – 0andriy Sep 12 '19 at 20:30
  • @shellter thanks, that works fine. – Norayr Ghukasyan Sep 12 '19 at 20:33
  • Also see [How to use Shellcheck](http://github.com/koalaman/shellcheck), [How to debug a bash script?](http://unix.stackexchange.com/q/155551/56041) (U&L.SE), [How to debug a bash script?](http://stackoverflow.com/q/951336/608639) (SO), [How to debug bash script?](http://askubuntu.com/q/21136) (AskU), [Debugging Bash scripts](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html), etc. – jww Sep 12 '19 at 21:02
  • I'm glad my idea helped. I hope that you see now how you can write a better question next time. Don't make people guess about what you are trying to do, please! ;-) OK? Good luck to all. – shellter Sep 12 '19 at 21:44

1 Answers1

2

Surround your variable with backtick ` :

./variables.sh `ls -l | wc -l`

As mentioned in comments, you can achieve this by below command as well :

./variables.sh $(ls -l | wc -l)
Pacifist
  • 3,025
  • 2
  • 12
  • 20