Question

I'm trying to write a Python or Bash script that outputs a bash command directly to the command line (i.e. as if I just typed it and could then hit enter to execute it).

How can I output the command in this fashion?

Was it helpful?

Solution

I don't think this is possible in bash. However, a reasonable subset of the functionality of the prompt can be simulated in bash 4 or later by using the read builtin and immediately executing the input with eval:

$ read -ei "ls -l"; eval "$REPLY"

Implicit line continuation is not available, such as if you end the line with a |; you'll need to explicitly provide the line-continuation character, and the next line will also have the initial text inserted, so you'd have to clear the line before continuing.

OTHER TIPS

With BASH you can easily do that using the select builtin command. Here there is a good example to start: http://linux.die.net/Bash-Beginners-Guide/sect_09_06.html

vim-slime accomplishes something similar by going through screen or tmux. Here's a proof of concept in Bash for running under tmux:

print_to_cmd_line() {
    printf '%s' "$*" | tmux load-buffer -
    tmux paste-buffer -d
}
cmd=( ls -l "hello world" )                # given an array as input
printf '%q ' -v cmd_quoted "${cmd[@]}"     # transform it to an eval-safe string
echo "Run the following: $cmd_quoted"      # ...which can then be run by the user

One way to use this from Python is to pipe content to bash (you could of course also be running the relevant bash script via subprocess.Popen()):

#!/usr/bin/env python
import sys 
cmd=['ls', '-l', 'hello world']
for element in cmd:
  sys.stdout.write('%s\0' % element)

...and in bash, to read that NUL-delimited input and write an eval-safe command:

#!/usr/bin/bash
arr=()
while IFS= read -r -d '' entry
  arr+=( "$entry" )
done
printf '%q ' "${arr[@]}"
printf '\n'

...then, to tie them together:

./python-gen-cmd | ./bash-gen-cmd

...will give you a safe command on stdout, ready to copy-and-paste or send over a SSH connection. This works even when your commands contain non-printable characters or similar oddness.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top