简体   繁体   中英

Linux bash script file concatenation

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

Should be:

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

if [ -f $file3 ]; then
    echo "concatenation of files successful"
fi
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.

单行


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM