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
4
  • 1
    possible duplicate of Open and write data on text file by bash/shell scripting Commented Jun 8, 2015 at 3: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? Commented Jun 8, 2015 at 6:10
  • The output file is completely blank. The output simply needs to be Text1, with Text2 underneath it. Commented Jun 8, 2015 at 10:28
  • Matt, your script is fine: you just forgot to insert the command echo at the start of lines 2 and 4. Commented Jun 9, 2015 at 12:58

2 Answers 2

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"
Sign up to request clarification or add additional context in comments.

3 Comments

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.
@MattSmith this is perhaps not the right community for you. You clearly do not have even the most basic understanding of shell scripting
Unfortunately, I have a class with a very subpar teacher, which leaves me to teach myself via what i can through assignments and books.
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

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.