简体   繁体   中英

Bash - extremely simple script redirecting output to file

Disclaimer: I'm very new to bash and for some reason I'm having a very hard time learning this one. The syntax seems very different depending on the website I visit.

I have a simple wrapper script that I want to test if a file is gzipped or not, and if so, to zcat the file to a new temporary file and open it in an editor. Here's part of the script:

if file $FILE | grep -q gzip
then
    timestamp=$(date +"%D_%T")
    $( zcat $FILE > tmp-$timestamp )
fi

I'm getting an error: "tmp-10/19/15_15:16:41: No such file or directory"

I tried removing the command substitution syntax or putting tmp-$timestamp in double quotes and I get the same error. If I remove the -$timestamp part, then it seems to work fine. Can someone tell me what's going on here? I'm clearing missing something very simple.

tmp-10/19/15_15:16:41 refers to a file named 15_15:16:41 in directory 19 which is a subdirectory of tmp-10 . If those directories and subdirectories do not exist, you cannot write to them.

Replace:

timestamp=$(date +"%D_%T")

With:

timestamp=$(date +"%F_%T")

This gives the date without the / .

As an example of this format:

$ date +"%F_%T"
2015-10-19_12:37:05

With %F , the year comes before the month which comes before the day. This means that your files will sort properly. For most people, that is an important advantage over %D .

Revised script

Your script can be simplified to:

if file "$file" | grep -q gzip
then
    zcat "$file" > "tmp-$(date +"%F_%T")"
fi

Notes:

  1. It is best practices not to use all caps for your shell variable. The system uses all caps for its variables and you don't want to accidentally overwrite one. Use lower case or mixed case and you'll be safe.

  2. File names, such as $file , should always be in double-quotes. Some day, someone will give you a file name with a space in it and you don't want that to cause your script to fail.

  3. The command substitution $(...) does not belong here. It has been removed.

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