请求编写可从键盘创建文本文件并检测文件类型的Shell脚本
Sure thing! Let's build a shell script that handles both creating a text file from keyboard input and checking its type. I'll include error handling to avoid accidental overwrites and break down how everything works so you understand each part.
1. Complete Shell Script
Save this code into a file (e.g., create-and-verify-file.sh):
#!/bin/bash # Ask user for the target filename echo "Enter the name of the file you want to create:" read filename # Check if the file already exists to prevent accidental overwrites if [ -f "$filename" ]; then echo "Heads up: The file '$filename' already exists." echo "Do you want to overwrite it? (type 'y' to confirm, any other key to cancel)" read overwrite_confirm if [[ "$overwrite_confirm" != "y" && "$overwrite_confirm" != "Y" ]]; then echo "Operation cancelled. No changes made." exit 0 fi fi # Capture user input and write it to the file echo "Now enter your content (press Ctrl+D when you're done):" cat > "$filename" # Verify the file was created successfully if [ ! -f "$filename" ]; then echo "Oops! Something went wrong—we couldn't create '$filename'." exit 1 fi # Detect and display the file's type echo -e "\nSuccess! File '$filename' has been created." echo "Here's the file type details:" file "$filename"
2. How It Works
Let's break down each section to make sense of what's happening:
- Filename Collection: The
readcommand grabs the filename you type in the terminal. - Existing File Check: The
[ -f "$filename" ]test checks if the file already exists. If it does, we ask for confirmation before overwriting—no more accidental data loss! - Content Input:
cat > "$filename"lets you type directly into the file. When you're finished, pressCtrl+D(this sends an "end-of-file" signal to stop capturing input). - Creation Verification: We double-check that the file was actually created before moving on, just in case something failed.
- File Type Detection: The
filecommand is perfect for this—it analyzes the file's actual content (not just the extension) to tell you exactly what type it is (e.g., ASCII text, UTF-8 text, even binary files if you accidentally paste non-text content).
3. How to Run the Script
- Make the script executable with this command:
chmod +x create-and-verify-file.sh - Run it in your terminal:
./create-and-verify-file.sh
Example Output
If you create a file named notes.txt with some plain text, you'll see something like this:
Enter the name of the file you want to create: notes.txt Now enter your content (press Ctrl+D when you're done): This is a test note for my shell script. It has multiple lines! Success! File 'notes.txt' has been created. Here's the file type details: notes.txt: ASCII text
内容的提问来源于stack exchange,提问作者Darius Ltu
相关产品推荐
相关产品推荐

