0

How do I make script exctract tar then enter the extracted tar directory?

I was trying

xtract

#!/bin/bash
tar -xvf $1 && cd $1

Usage example

suppose there's foo.tar.xz so how to use it: ./xtract foo.tar.xz

So you can see my problem is in argument, I succeed extract it but failed in enter it because of file name extension. So how do i remove it in argument so i can enter foo directory

0

1 Answer 1

1

A shell script can never change the working directory for its parent process (the shell invoking the script). So although you may change to the created directory in the script, as soon as the script terminates (and its environment is destroyed, including the fact that a particular directory was the current directory for the process), you will find yourself in whatever directory you were when you executed the script.

However, a shell function executes within the current shell session and may set the current working directory for the session with cd in the way that you expect.

The following is a shell function that tries to extract a tar archive given on its command line and, if that is successful, changes into the directory provided by the archive's name, with .tar removed from the end (this is done using a standard parameter expansion).

xtract () {
    tar -x -v -f "$1" &&
    cd -- "${1%.tar}"
}

You could define this function by just pasting the above into your shell, or you could add it to wherever you ordinarily add shell functions and aliases, and it would be available in the next shell session you start.

If you want to support xz-compressed tar archives, you may need to change the above function so that it uses the correct options to tar or your system (-J or --xz with GNU tar, for example), or passes the archive from xz -d -c -- "$1" via a pipe to tar -x -v -f -. You also have to adjust the cd command so that it deletes .tar.xz rather than just .tar from the end of the given archive's filename.

If you have a smart enough tar that uses the filename suffix to determine that compression algorithm correctly, you could get by with

xtract () {
    tar -x -v -f "$1" &&
    cd -- "${1%.tar.*}"
}

The difference to the previous function is that we're stripping .tar followed by a dot and then any string from the end of the archive's name to arrive at the directory that we try to cd into.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.