dwjohnston
dwjohnston

Reputation: 11812

How do I write a bash script to open a CLI program and then execute some commands?

I have CLI tool I need open (indy), and then execute some commands.

So I want to write a bash script to do this for me. Using python as example it might look like:

#!/bin/bash

python
print ("hello world")

But ofcourse all this does is open python and doesn't enter the commands. How I would I make this work?

My development environment is Windows, and the run time environment will be a linux docker container.

Edit: It looks like this approach will work for what I'm actually doing, it seems like Python doesn't like it though. Any clues why?

Upvotes: 0

Views: 1621

Answers (2)

Bach Lien
Bach Lien

Reputation: 1060

How to embed a foreign script: We can comment out the "foreign" script part and then "embeded" it in a bash script; then use sed or some way to "extract" that part and execute it.

sed -n '                    ## do not automatically print
  /^### / {                 ## for all lines that begins with "### "
    s:^### ::;              ## delete that "### "
    s:FUNC:$1:g;            ## replace all "FUNC" with "$1"
    p                       ## print that line
}'

An example to "embed" a python script into a bash script:

#!/bin/bash

ME="$0"

callEmbeded() {
  sed -n "/^### /{s:^### ::;s:FUNC:$1:g;p}" <"$ME" | python
}

while read -n1 KEY; do
  case "x$KEY" in
    x1)
      callEmbeded func1
      ;;
    x2)
      callEmbeded func2
      ;;
    xq)
      exit
      ;;
    *)
      echo "What do you want?"
  esac
done

### # ----
### # python part
###
### def func1():
###   print ("hello world!")
###
### def func2():
###   print ("hi there!")
###
### if __name__ == '__main__':
###   FUNC()

A similar example to "embed" a bash script into another one:

# cat <<EOF >/dev/null

ME="$0"

callEmbeded() {
  cut -c3- <"$ME" | bash -s "$1"
}

while read -n1 KEY; do
  case "x$KEY" in
    x1)
      callEmbeded func1
      ;;
    x2)
      callEmbeded func2
      ;;
    xq)
      exit
      ;;
    *)
      echo "What do you want?"
  esac
done

# EOF
# ## ----
# ## embeded part
#
# func1() {
#     echo "hello world."
# }
#
# func2() {
#     echo "hi there."
# }
#
# eval "$@"

Upvotes: 1

Jesse
Jesse

Reputation: 2074

From the comments, you need to create a .py file with the commands you wan't to execute.

#!/bin/bash
python <path-to-file>.py

Other option of course, is to pass in the commands on the cli with the flag -c (refer to python man page)

#!/bin/bash
python -c "print('hello')

Will be the same with indy. You cannot run indy-cli and enter commands on subsequent lines in your script. You need to use indy-cli to run it's own set of commands by passing those commands to the indy-cli as an argument. (in this case as a it's own script file).

#!/bin/bash
indy-cli <path-to-indy-file-that-contains-indy-commands>

Upvotes: 1

Related Questions