Ergec
Ergec

Reputation: 11824

how to convert multiline linux commands to one line of command

Can someone please explain me how to use ">" and "|" in linux commands and convert me these three lines into one line of code please?

mysqldump --user=*** --password=*** $db --single-transaction -R > ${db}-$(date +%m-%d-%y).sql
tar -cf ${db}-$(date +%m-%d-%y).sql.tar ${db}-$(date +%m-%d-%y).sql
gzip ${db}-$(date +%m-%d-%y).sql.tar
rm ${db}-$(date +%m-%d-%y).sql (after conversion I guess this line will be useless)

Upvotes: 2

Views: 545

Answers (4)

paxdiablo
paxdiablo

Reputation: 881623

The GNU tar program can itself do the compression normally done by gzip. You can use the -z flag to enable this. So the tar and gzip could be combined into:

tar -zcf ${db}-$(date +%m-%d-%y).sql.tar.gz ${db}-$(date +%m-%d-%y).sql

Getting tar to read from standard input for archiving is not a simple task but I would question its necessity in this particular case.

The intent of tar is to be able to package up a multitude of files into a single archive file but, since it's only one file you're processing (the output stream from mysqldump), you don't need to tar it up, you can just pipe it straight into gzip itself:

mysqldump blah blah | gzip > ${db}-$(date +%m-%d-%y).sql.gz

That's because gzip will compress standard input to standard output if you don't give it any file names.

This removes the need for any (possibly very large) temporary files during the compression process.

Upvotes: 2

flolo
flolo

Reputation: 15496

I dont see the point in using tar: You just have one file, and for compression you call gzip explicit. Tar is used to archive/pack multiple files into one.

You cammandline should be (the dump command is shorted, but I guess you will get it):

mysqldump .... | gzip > filename.sql.gz

Upvotes: 2

Jeremiah Gowdy
Jeremiah Gowdy

Reputation: 5622

To append the commands together in one line, I'd put && between them. That way if one fails, it stops executing them. You could also use a semicolon after each command, in which case each will run regardless if the prior command fails or not.

You should also know that tar will do the gzip for you with a "z" option, so you don't need the extra command.

Paxdiablo makes a good point that you can just pipe mysqldump directly into gzip.

Upvotes: 0

Sergey Kuznetsov
Sergey Kuznetsov

Reputation: 8721

You can use next script:

#!/bin/sh
USER="***"
PASS="***"
DB="***"

mysqldump --user=$USER --password=$PASS $DB --single-transaction -R | gzip > ${DB}-$(date +%m-%d-%y).sql.gz

You can learn more about "|" here - http://en.wikipedia.org/wiki/Pipeline_(Unix). I can say that this construction moves output of mysqldump command to the standard input of gzip command, so that is like you connect output of one command with input of other via pipeline.

Upvotes: 2

Related Questions