bashup / mdsh

Multi-lingual, Markdown-based Literate Programming... in run-anywhere bash
MIT License
185 stars 15 forks source link

Use output from one block as a variable in another? #4

Closed shadowrylander closed 6 years ago

shadowrylander commented 6 years ago

Hello!
     The description pretty much says it all; for example, running ls -a in a directory, getting " " back (i.e. nothing), using that in, say, a python block?
     Thank you once again for the help!

pjeby commented 6 years ago

The correct answer to any mdsh programming question is, "how would you do it in a shell script?", because mdsh is just an extensible translator from markdown to shell script.

For example:

```shell
somevar="$(ls -a)"
```

```python |python /dev/stdin "$somevar"
import sys
print(sys.argv[1])  # contents of $somevar
```

But of course you can avoid repeating things by defining translator functions of your own. For example:

```shell @mdsh
mdsh-compile-pyargs() {
    printf "python -c %q %s\n" "$1" "${2#*$mdsh_lang}"
}
```

```shell
somevar="$(ls -a)"
```

```python @pyargs "$somevar"
import sys
print(sys.argv[1])  # contents of $somevar
```

This second script defines a pyargs language compiler that rewrites @pyargs blocks to python -c 'block-contents' ..., making it easier to use. If you mdsh -c the above, you get:

somevar="$(ls -a)"

python -c $'import sys\nprint(sys.argv[1])  # contents of $somevar\n'  "$somevar"

which as you can see is a very basic shell script to do what was asked.

mdsh-compile-X functions just output the needed shell code given their arguments. All of this is in the documentation. If you don't know how to write shell scripts, mdsh can't really help you.