Pipe to another command bash - bash

I cannot seem to get my bash script to work, i want to pipe the output from the gunzip command to another command but it is not working, can anyone help me?
The gunzip command outputs a tar file that i want to then use the tar command to put back yo the original file.
# let the user choose what they want to Restore
echo -n "Select the file or directory you want to Restore"
read Chosendata
echo -e "Starting Restore"
# unziping files
gunzip ${Chosendata} | tar xvf - #Here
# end the restore.
echo -e "Restore complete"

Use gunzip -c.
-c, --stdout write on standard output, keep original files unchanged
Or tar only: tar -xzf ${Chosendata}.

Related

Short tar script: 'command not found' when trying to add today's date to a compressed file name

I'm trying to create a script that will do the following:
create /home/testuser/backup as a directory if it doesn't exist (and won't show an error message if it does exist)
obtain the current date and store it as a variable
Using Tar:
backup the entire projectfiles directory
backup is compressed, in gzip format, in archive format
uses the stored variable to include the date in the tar filename
the backup goes to the /home/testuser/backup directory
create a log file called testuser.log with all messages generated by the tar command (using verbose mode)
save the log file in /home/testuser/backup/testuser.log
I'm having trouble with the command syntax and I don't quite understand what I'm doing wrong.
cd /home/testuser
mkdir -p /home/testuser/backup
today=$(date'+%d-%m-%y')
tar -zcvf testuserbackup-$today.tar.gz projectfiles &&
testuserbackup-$today.tar.gz /home/testuser/backup
testuserbackup-$today.tar.gz >> testuser.log 2>/dev/null
mv testuser.log /home/testuser/backup
When I try to run the script I get the following terminal output:
./script2.sh: line 6: date+%d-%m-%y: command not found
projectfiles/
projectfiles/budget/
projectfiles/budget/testuserbudget1.txt
projectfiles/budget/testuserbudget2.txt
projectfiles/old/
projectfiles/old/testuserold2.txt
projectfiles/old/testuserold1.txt
projectfiles/documents/
projectfiles/documents/testuserdoc2.txt
projectfiles/documents/testuserdoc1.txt
./script2.sh: line 7: testuserbackup-.tar.gz: command not found
I'm open to any suggestions. This task is from an old assignment from last semester that I'm revisiting for fun...
According to my old assignment notes this task should be able to be done in no more than 4 lines of code.
**EDIT:**Finished script (with assistance of John)
#!/bin/bash
mkdir -p /home/testuser/backup
today=$(date '+%d-%m-%y')
tar -zcvf backup/testuserbackup-"$today".tar.gz projectfiles >
backup/testuser.log 2>&1
You're missing a space:
today=$(date '+%d-%m-%y')
# ^
Additionally, these lines should all be combined:
tar -zcvf testuserbackup-$today.tar.gz projectfiles &&
testuserbackup-$today.tar.gz /home/testuser/backup
testuserbackup-$today.tar.gz >> testuser.log 2>/dev/null
mv testuser.log /home/testuser/backup
The log file needs to be created in the same line as the tar command, and making the tarball and the log file show up in the right location can be done by writing out their full paths. That gets rid of the need to move them later.
tar -zcvf backup/testuserbackup-"$today".tar.gz projectfiles > backup/testuser.log 2>&1
It's a good idea to capture stderr as well as stdout, so I changed 2>/dev/null to 2>&1.

Script to download, gunzip merge files and gzip the fil again?

My script skills are really limited so I wonder if someone here could help me. I would like to download 2 files, run gunzip, run a command called tv_merge and then gzip the new file. Here's what I Would like to be run from a script.
I would like to download two files (.gz) with wget:
wget -O /some/where/file1.gz http://some.url.com/data/
wget -O /some/where/file2.gz http://some.url.com/data/
Then gunzip the 2 files:
gunzip /some/where/file1.gz
gunzip /some/where/file2.gz
After that run a command called Tv_merge:
tv_merge -i /some/where/file1 -m /some/where/file2 -o newmaster.xml
After tv_merge. I would like to gzip the file:
gzip newmaster.xml
I would like to run all these commands in that order from a script, and I would like to put that to be run let's see every 8h like a crontab.
I'm assuming that file names are static. with provided information this should get you going.
#!/bin/bash
echo "Downloading first file"
wget -O /some/where/file1.gz http://some.url.com/data/
echo "First Download Completed"
echo "Downloading Second file"
wget -O /some/where/file2.gz http://some.url.com/data/
echo "Second Download Completed"
gunzip /some/where/file1.gz
gunzip /some/where/file2.gz
echo "Running tv_merge"
tv_merge -i /some/where/file1 -m /some/where/file2 -o newmaster.xml
gzip -c newmaster.xml > /some/where/newmaster.xml.gz
echo "newmaster.xml.gz is ready at /some/where/newmaster.xml.gz"
Save this to a file for example script.sh then chmod +x script.sh and you can run it with bash script.sh.

Bash gunzip error

While trying to restore the file "derp" the terminal prints
derp0000644000175000017500000000000512343302711011660 0ustar UserUserDerp
and does not unpack the files , i am confused can someone help me ?
# let the user choose what they want to Restore
echo -n "Select the file or directory you want to Restore"
read chosendata
echo -e "Starting Restore"
# unziping files
gunzip -c ${chosendata}
# end the backup.
echo -e "Restore complete"
"gunzip -c" unzips to stdout rather than to a file. Use "man gunzip" to review options for gunzip.

tar: file changed as we read it

I am using make and tar to backup. When executing makefile, tar command shows file changed as we read it. In this case,
the tar package is ok when the warning comes up
but it stops the tar command for the following backup
the file showing the warning in fact doesn't change -- it is really strange that the warning comes up
the files showing the warning come up randomly, I mean, everytime I run my makefile, the files showing the warning are different
--ignore-failed-read doesn't help. I am using tar 1.23 in MinGW
I just changed my computer to WIN7 64 bit. The script works well in old WIN7 32 bit. But the tar version is not as new as the 1.23.
How can I stop the tar's warning to stop my backup following the warning?
Edit-2: it might be the reason
As I said above, the bash shell script worked well in my old computer. Comparing with the old computer, the msys version is different. So is the version of tar command. In the old computer, tar is 1.13.19 and it is 1.23 in the new computer. I copied the old tar command without copying its dependency msys-1.0.dll to the new computer and renamed it tar_old. And I also updated the tar command in the shell script and run the script. Then everything is ok. So, it seemed that the problem is the tar command. I am sure that there is no any file changed when taring. Is it a bug for tar command in new version? I don't know.
Edit-1: add more details
The backup is invoked by a bash shell script. It scans the target directory and builds makefile then invokes make to use tar command for backup. Followed is a typical makefile built by the bash shell script.
#--------------------------------------------
# backup VC
#--------------------------------------------
# the program for packing
PACK_TOOL=tar
# the option for packing tool
PACK_OPTION=cjvf
# M$: C driver
WIN_C_DIR=c:
# M$: D driver
WIN_D_DIR=d:
# M$: where the software is
WIN_PRG_DIR=wuyu/tools
# WIN_PRG_DIR=
# where to save the backup files
BAKDIR=/home/Wu.Y/MS_bak_MSYS
VC_FRAMEWORK=/home/Wu.Y/MS_bak_MSYS/tools/VC/VC_framework.tar.bz2
VC_2010=/home/Wu.Y/MS_bak_MSYS/tools/VC/VC_2010.tar.bz2
.PHONY: all
all: $(VC_FRAMEWORK) $(VC_2010)
$(VC_FRAMEWORK): $(WIN_C_DIR)/$(WIN_PRG_DIR)/VC/Framework/*
#$(PACK_TOOL) $(PACK_OPTION) "$#" --ignore-failed-read /c/$(WIN_PRG_DIR)/VC/Framework
$(VC_2010): $(WIN_C_DIR)/$(WIN_PRG_DIR)/VC/VS2010/*
#$(PACK_TOOL) $(PACK_OPTION) "$#" --ignore-failed-read /c/$(WIN_PRG_DIR)/VC/VS2010
As you can see, the tar package is stored in ~/MS_bak_MSYS/tools/VC/VC_2010.tar.bz2. I run the script in ~/qqaa. ~/MS_bak_MSYS is excluded from tar command. So, the tar file I am creating is not inside a directory I am trying to put into tar file. This is why I felt it strange that the warning came up.
I also encounter the tar messages "changed as we read it". For me these message occurred when I was making tar file of Linux file system in bitbake build environment. This error was sporadic.
For me this was not due to creating tar file from the same directory. I am assuming there is actually some file overwritten or changed during tar file creation.
The message is a warning and it still creates the tar file. We can still suppress these warning message by setting option
--warning=no-file-changed
(http://www.gnu.org/software/tar/manual/html_section/warnings.html
)
Still the exit code return by the tar is "1" in warning message case:
http://www.gnu.org/software/tar/manual/html_section/Synopsis.html
So if we are calling the tar file from some function in scripts, we can handle the exit code something like this:
set +e
tar -czf sample.tar.gz dir1 dir2
exitcode=$?
if [ "$exitcode" != "1" ] && [ "$exitcode" != "0" ]; then
exit $exitcode
fi
set -e
Although its very late but I recently had the same issue.
Issue is because dir . is changing as xyz.tar.gz is created after running the command. There are two solutions:
Solution 1:
tar will not mind if the archive is created in any directory inside .. There can be reasons why can't create the archive outside the work space. Worked around it by creating a temporary directory for putting the archive as:
mkdir artefacts
tar -zcvf artefacts/archive.tar.gz --exclude=./artefacts .
echo $?
0
Solution 2:
This one I like. create the archive file before running tar:
touch archive.tar.gz
tar --exclude=archive.tar.gz -zcvf archive.tar.gz .
echo $?
0
If you want help debugging a problem like this you need to provide the make rule or at least the tar command you invoked. How can we see what's wrong with the command if there's no command to see?
However, 99% of the time an error like this means that you're creating the tar file inside a directory that you're trying to put into the tar file. So, when tar tries to read the directory it finds the tar file as a member of the directory, starts to read it and write it out to the tar file, and so between the time it starts to read the tar file and when it finishes reading the tar file, the tar file has changed.
So for example something like:
tar cf ./foo.tar .
There's no way to "stop" this, because it's not wrong. Just put your tar file somewhere else when you create it, or find another way (using --exclude or whatever) to omit the tar file.
Here is a one-liner for ignoring the tar exit status if it is 1. There is no need to set +e as in sandeep's script. If the tar exit status is 0 or 1, this one-liner will return with exit status 0. Otherwise it will return with exit status 1. This is different from sandeep's script where the original exit status value is preserved if it is different from 1.
tar -czf sample.tar.gz dir1 dir2 || [[ $? -eq 1 ]]
To enhance Fabian's one-liner; let us say that we want to ignore only exit status 1 but to preserve the exit status if it is anything else:
tar -czf sample.tar.gz dir1 dir2 || ( export ret=$?; [[ $ret -eq 1 ]] || exit "$ret" )
This does everything sandeep's script does, on one line.
Simply using an outer directory for the output, solved the problem for me.
sudo tar czf ./../31OCT18.tar.gz ./
Exit codes for tar are restricted, so you don't get to much information.
You can assume that ec=1 is safe to ignore, but it might trip - i.e. the gzip-example in other posts (exit code from external programs).
The reason for the file changed as we read it error/warning can be varying.
A log file inside the directory.
Writing to a tar file in the same directory you are trying to back up.
etc.
Possible workarounds can involve:
exclude known files (log files, tar-files, etc)
ensure log files are written to other directories
This can be quite involved, so you might want to still just run the tar command and preferably safely ignore some errors / warnings.
To do this you will have to:
Save the tar output.
Save the exit code
Check the output against known warnings and errors, not unlike tar's own ignore.
Conditionally pass another exit code to the next program in the pipe.
In OP's case this would have to be wrapped in a script and run as PACK_TOOL.
# List of errors and warnings from "tar" which we will safely ignore.
# Adapt to your findings and needs
IGNORE_ERROR="^tar:.*(Removing leading|socket ignored|file changed as we read it)"
# Save stderr from "tar"
RET=$(tar zcf $BACKUP --exclude Cache --exclude output.log --exclude "*cron*sysout*" $DIR 2>&1)
EC=$? # Save "tar's" exit code
echo "$RET"
if [ $EC -ne 0 ]
then
# Check the RET output, remove (grep -v) any errors / warning you wish to ignore
REAL_ERRORS=$(echo "$RET" | grep "^tar: " | grep -Ev "${IGNORE_ERROR:?}")
# If there is any output left you actually got an error to check
if [ -n "$REAL_ERRORS" ]
then
echo "ERROR during backup of ${DIR:?} to ${BACKUP:?}"
else
echo "OK backup of (warnings ignored) ${DIR:?}"
EC=0
fi
else
echo "OK backup of ${DIR:?}"
fi
It worked for me by adding a simple sleep timeout of 20 sec.
This might happen if your source directory is still writing. Hence put a sleep so that the backup would finish and then tar should work fine. This also helped me in getting the right exit status.
sleep 20
tar -czf ${DB}.${DATE}.tgz ./${DB}.${DATE}
I am not sure does it suit you but I noticed that tar does not fail on changed/deleted files in pipe mode. See what I mean.
Test script:
#!/usr/bin/env bash
set -ex
tar cpf - ./files | aws s3 cp - s3://my-bucket/files.tar
echo $?
Deleting random files manually...
Output:
+ aws s3 cp - s3://my-bucket/files.tar
+ tar cpf - ./files
tar: ./files/default_images: File removed before we read it
tar: ./files: file changed as we read it
+ echo 0
0
Answer should be very simple: Don't save your tar file while "Taring" it in the same directory.
Just do: tar -cvzf resources/docker/php/php.tar.gz .
Eventually,
it will tar the current directory and save it to another directory.
That's easy peasy, lemon squeezy fellas

Shell Scripts with conditional echos

How do I exclude what my script is doing and only have echo's print?
For instance, i am taring a directory and I don't want every file it tar's to echo.. only the echo command.
#! /bin/bash
clear
echo "Compressing the files"
cd ~/LegendaryXeo/html/
tar --exclude=".git" -cvf site.tar *
mv site.tar ~/LegendaryXeo/work/
cd ~/LegendaryXeo/work/
clear
echo "Extracting the site"
tar -xvf site.tar
echo "Deleting Tar"
cd ~/LegendaryXeo/work/
rm -f site.tar
clear
echo "Copying files to server"
scp -r ~/LegendaryXeo/work/* user#site.com:~/../../domains/
Redirect the output of tar to /dev/null:
tar [your options] [files] &> /dev/null
Any echo command you have in your script will still output to the screen.

Resources