0

I would like to run commands such as "history" or "!23" off of a pipe.

  1. How might I achieve this?
  2. Why does the following command not work?
echo "history" | xargs eval $1
agc
  • 7,973
  • 2
  • 29
  • 50
Zero
  • 3
  • 2

2 Answers2

2

To answer (2) first:

  • history and eval are both bash builtins. So xargs cannot run either of them.
  • xargs does not use $1 arguments. man xargs for the correct syntax.

For (1), it doesn't really make much sense to do what you are attempting because shell history is not likely to be synchronised between invocations, but you could try something like:

{ echo 'history'; echo '!23'; } | bash -i

or:

{ echo 'history'; echo '!23'; } | while read -r cmd; do eval "$cmd"; done

Note that pipelines run inside subshells. Environment changes are not retained:

x=1; echo "x=2" | while read -r cmd; do eval "$cmd"; done; echo "$x"
jhnc
  • 11,310
  • 1
  • 9
  • 26
  • Thank you I appreciate you taking the time distribute some of your knowledge. I would upvote this but I don't have enough "reputation". – Zero Mar 12 '19 at 17:29
0

You can try like this First redirect the history commands to a file (cut out the line numbers)

history | cut -c 8- > cmd.txt

Now Create this script hcmd.sh(Referred to this Read a file line by line assigning the value to a variable)

#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
    echo "Text read from file: $line"
    $line
done < "cmd.txt"

Run it like this

./hcmd.sh
Raghuram
  • 3,937
  • 2
  • 19
  • 25