How to extract tar files to specific directory (folder) in Linux

So I need to extract backup-lastest.tar.gz to the /var/www/html/ directory. How can I extract all files to that specific directory on Linux server? I am using Red Hat Enterprise Linux 8 EC2 cloud server. Please provide hints.

Yes the tar command provides the -C DIR option to change directory into the DIR and perform operation such as extrating files.

Extracting tar files to a specific directory

Say you have a file named foo.tgz and want to extract to the /tmp/ folder on Linux. You would write:

tar -zxvf foo.tgz /tmp/

Verify it:

cd /tmp/
ls -l

Extract .tar.gz files to /var/www/html/ directory

You must run the following as root or www-data user:

sudo tar -zxvf backup-lastest.tar.gz -C /var/www/html/
## verification ##
cd /var/www/html
ls -l

Where the tar options are as follows:

  1. -z : Deal with compressed gzip file
  2. -x : Extract file
  3. -v : Verbose output
  4. -f : Input Filename
  5. -C /var/www/html/ : Destination directory i.e. change to /var/www/html/ directory before extracting files.

Extract only specific files from tar ball archive

Say you only need logo.jpg and put into the /var/www/html/, you would do:

sudo  tar -zxvf backup-lastest.tar.gz logo.jpg -C /var/www/html/
sudo  tar -zxvf backup-lastest.tar.gz css/main.css logo.jpg -C /var/www/html/

See our guide for more information:

Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki