0

Hi in my script i've concatenated two files into a new file called output.txt. Am having trouble checking that output.txt file does exist to then print a "concatenation successful" message. The concatenation appears to work and create a new file.

cat $file1 $file2 >> output.txt     

file3="$output.txt"                #incorrect?

if [ -e $file3 ]                             
then
    echo "concatenation of files successful"
fi
1
  • Remove the dollar sign: file3="output.txt". $output is being replaced by a variable named output (which does not exist in the snippet posted here). If you move the file3 variable above cat, you can use it for the output redirection as well to avoid repeating the filename twice. Commented Apr 2, 2019 at 23:46

3 Answers 3

1

Should be:

file3="output.txt"
cat $file1 $file2 >> $file3

if [ -f $file3 ]; then
    echo "concatenation of files successful"
fi
Sign up to request clarification or add additional context in comments.

4 Comments

That -f doesn't fix the problem. In fact -e works just fine too.
Just fixed it - now should be ok
I changed to upvote because @cfillion only added his answer as a comment. So even though this is edited this now is the correct answer. @phebus - note that in a shell script you don't need to have ; after if and before then
It now tries to run a command named file3. There should not be spaces around the equal sign.
1
file3="output.txt"
cat $file1 $file2 >> $file3

if [ $? == 0 ]; then
    echo "concatenation of files successful"
fi

Checking the file's existence doesn't mean that the files concatenated successfully. It means that the file exists.

Consider that:

cat $file1 $file2(missing) >> $file3
cat $file1(missing) $file2 >> $file3

would make $file3 exist.

Checking last operation exit value with $? accounts for the whole operation working successfully.

Also, unless you're specifically looking to append >> to existing file, you will ALWAYS append. So your file will always exist after the first operation.

Comments

0

In single line


cat $file1 $file2 >> output.txt && echo 'Success' || echo 'Failed'

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.