1

I want to write Bash script witch will allow me to run commands from a text file.

In file will be special word: "secretcommand" and the proper command in next line.

Example of text file:

This is

my

secretcommand

pwd

bash

script

Now I want in my script to find a "secretcommand". I wanted to use grep -n so I could get the line of this word and then somehow add + 1 to that line so I get number of next line where is proper command. And finally I want to run this command. I wanted use sed -f but it wasn't workin or I'm doing something wrong.

Can you help me please?

1

3 Answers 3

1

This script will take one argument, the path for your text file:

#!/bin/bash
while read -r line
do
  [[ "$line" =~ ^secretcommand$ ]] || continue
  read -r cmd || break
  eval "$cmd"
  break
done<"$1"

It requires the whole line to match exactly secretcommand, with no extra spacing (this can be modified by altering the regular expression matching between double brackets [[ ]].

Please note that using "eval" on arbitrary data is generally not a good idea from a security perspective, but given your purpose is precisely to execute code from data files, I assume you understand the risks.

Sign up to request clarification or add additional context in comments.

Comments

0

You can try to use awk to echo the proper command and then execute it, something like this:

awk '/secretword/ { flag = "1" } { if(flag == "1" && $1 != "secretword") { print $1; exit 0 } }' <file | bash -

Comments

0

This script take the file with secret command as the commandline argument.

#!/bin/bash

words=`cat $1`
found=0
command=''
for word in ${words[@]};
do
   if [ $word = 'secretcommand' ]; then
      found=1
   elif [ $found -eq 1 ]; then
      found=0
      command=$word
   fi
done
if [ $command != '' ]; then
   $command  # run the found command
fi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.