如何扩展Shell脚本:在指定目录生成domains.txt并写入多行域名
扩展目录创建与多行域名写入脚本
以下是扩展后的完整脚本,可实现创建指定目录,并将用户输入的多行域名写入该目录下的domains.txt文件:
echo "Enter directory name" read dirname dir_path="/root/test1/test2/$dirname" if [ ! -d "$dir_path" ] then echo "Directory doesn't exist. Creating now" mkdir "$dir_path" echo "Directory created" else echo "Directory exists" fi echo "Enter domains (one per line, press Ctrl+D when done):" cat > "$dir_path/domains.txt" echo "Domains have been saved to $dir_path/domains.txt"
关键扩展说明:
- 路径统一管理:将目标目录路径存入
dir_path变量,减少重复代码,避免因路径拼写错误引发问题。 - 多行输入处理:通过
cat > "$dir_path/domains.txt"接收用户多行输入,用户每行输入一个域名,按下Ctrl+D即可结束输入,内容会自动按行写入文件,保持每个域名单独占一行的格式。 - 兼容已有目录:无论目录是新创建还是已存在,都会执行域名写入步骤,支持在已有目录下更新域名列表。
- 特殊字符兼容:用双引号包裹所有包含变量的路径,确保路径中包含空格等特殊字符时脚本仍能正常运行。
内容的提问来源于stack exchange,提问作者user7778555
相关产品推荐
相关产品推荐

