简体   繁体   中英

How do I use tar using an absolute path from user input to backup a directory?

I have a script that gets the input from the user as an absolute path (using the fselect dialog box).

backupdir=$(user_select "choose a directory backup destination");

I used

tar cvzf backup.tar.gz $backupdir

however this includes the absolute directory path (*1) so instead I attempted (out-with the script):

tar czvf backup.tar.gz -C $PATH directory-to-backup

Therefore, in my script I can use:

pathtodir = dirname $backupdir 

to get the $PATH of the backup directory but I need the name of the directory I wish to backup ie:

dirname = ..
tar czvf backup.tar.gz -C $PATH $dirname

How do I get the name of $dirname?

1 - "Removing leading `/' from member name"

Okay, to be honest I had some difficulty to figure out the question at first. I think we sorted that in the comments.

So you have $backupdir which contains the absolute path to the backup directory, plus $pathtodir which is a parent directory of the backup directory.

You can now use string substitution in Bash as follows:

# Replace $pathtodir with empty string inside $backupdir
relativepath=${backupdir//$pathtodir/}
# Now remove the leading slash, if any
relativepath=${relativepath#/}

If I misunderstood something still, let me know and I'll adjust the answer accordingly.

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