2

I have to write a script in linux that saves one line of text to a file and then appends a new line. What I currently have is something like:

read "This line will be saved to text." Text1
$Text1 > $Script.txt
read "This line will be appended to text." Text2
$Text2 >> $Script.txt
Cris
  • 2,002
  • 4
  • 30
  • 51
Matt Smith
  • 63
  • 1
  • 6
  • 1
    possible duplicate of [Open and write data on text file by bash/shell scripting](http://stackoverflow.com/questions/11162406/open-and-write-data-on-text-file-by-bash-shell-scripting) – that other guy Jun 08 '15 at 03:33
  • In your output file, did you want to append content which is already on the second line, or overwrite whatever is already on the second line? – Andy J Jun 08 '15 at 06:10
  • The output file is completely blank. The output simply needs to be Text1, with Text2 underneath it. – Matt Smith Jun 08 '15 at 10:28
  • Matt, your script is fine: you just forgot to insert the command `echo` at the start of lines 2 and 4. – davidedb Jun 09 '15 at 12:58

2 Answers2

0

One of the main benefits of scripting is that you can automate processes. Using read like you have destroys that. You can accept input from the user without losing automation:

#!/bin/sh
if [ "$#" != 3 ]
then
  echo 'script.sh [Text1] [Text2] [Script]'
  exit
fi
printf '%s\n' "$1" "$2" > "$3"
Zombo
  • 1
  • 62
  • 391
  • 407
  • All that does is output script.sh [Text1] [Text2] [Script] for me. I'm looking to save user input into a variable and then put that into a .dat file. Not really looking to automate much, just looking to complete this assignment as needed. – Matt Smith Jun 08 '15 at 04:13
  • @MattSmith this is perhaps not the right community for you. You clearly do not have even the most basic understanding of shell scripting – Zombo Jun 08 '15 at 04:15
  • Unfortunately, I have a class with a very subpar teacher, which leaves me to teach myself via what i can through assignments and books. – Matt Smith Jun 08 '15 at 04:21
0

Assuming you don't mind if the second line of your output file is overwritten (not appended) every time the script is run; this might do.

#!/bin/sh
output_file=output.dat
if [ -z "$1" ] || [ -z "$2" ]; then echo Need at least two arguments.; fi
line1=$1; line2=$2
echo $line1 > $output_file
echo $line2 >> $output_file

Executing the script:

# chmod +x foo.sh 
# ./foo.sh 
Need at least two arguments.
# ./foo.sh hello world
# cat output.dat 
hello
world
Andy J
  • 1,479
  • 6
  • 23
  • 40