0

I need to create bash script file, which after its launch does following.

1) Suppose after launching the script I enter the text 'abc'. Then the script must automatically generate commands

cat text.txt
echo '123' > text.txt
echo 'abc' >>text.txt
echo '456' >>text.txt

2) After doing that I need to execute some commands (like compile the program etc.).

How to create bash script which executes these tasks?

1
  • 1
    You'll probably want to look at manual the bash builtin read and the -n flag for echo. But take a look at sed and rethink your concept as loading your phrase into a variable, say $NEW, and then running sed 's/123456/123'"$NEW"'456' Which probably has it own issues, especially if $NEW gets a slash inside it, but its a first step. Commented May 24, 2016 at 15:34

1 Answer 1

1

If the top and bottom are fixed, it can be something like:

cat top.txt /dev/stdin bottom.txt > text.txt 
# with cat, - works the same as /dev/stdin

or

{ 
  echo 123 #top.txt
  cat
  echo 456 #bottom.txt
} > text.txt 

followed by your compilation commands

cat top.txt /dev/stdin bottom.txt > text.txt
gcc whatever 

The first line should be a shebang line specifying your interpreter, unless you're OK with /bin/sh

 #!/bin/bash
 cat top.txt /dev/stdin bottom.txt > text.txt
 gcc whatever

If you then mark the script executable with chmod +x the_script, ./the_script will be equivalent to /bin/bash ./the_script.

If you want the scrip to abort a command fails, start it with set -e (or make the shebang line (#!/bin/bash -e).

Edit:

cat expects a whole file (until you enter ctr-d -- the end of file marker). If you want just one line, you can do read -r something; printf '%s\n' "$something" or head -n1.

You can read the help pages of the commands with man $command or help $command.

3
  • Thank You very much! But when I launch 'cat top.txt /dev/stdin bottom.txt > text.txt', it doesn't execute (i.e, it enters the input mode, I enter something and write "Enter", but it doesn't going out the input mode). What is the problem? Commented May 24, 2016 at 15:41
  • Oh, cat expects a whole file (until you enter ctr-d -- the end of file marker). If you want just one line, you can do read -r something; printf '%s\n' "$something" or head -n1. Commented May 24, 2016 at 15:44
  • Thank You one more! And, if You please, may I ask You about details of Your answer, if I'll stuck? Commented May 24, 2016 at 15:47

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.