简体   繁体   中英

Bash script to gzip specific file extensions

I was given a script that finds all html files and compresses them individually to a new location

#!/bin/bash
for i in .html; do
gzip < $i > /backup/full/$i
done

I'm not sure I fully understand how it works though, as it only functions if it is located in the same directory as the files. What if for whatever reason the script is located elsewhere?

Trying something like this to add the file path results in both original and destination paths to be combined and an error

for i in /html/directory/*.html; do
gzip < $i > /backup/full/$i
done

Thank you for your time

You need to remove the original directory prefix when constructing the output filename.

gzip < "$i" > /backup/full/"$(basename "$i").gz"

or using a parameter expansion operator:

gzip < "$i" > /backup/full/"${i##*/}".gz

Don't forget to quote your variables, so that filenames with whitespace will be processed properly.

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