Bash Script to create another file
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8866837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash Script to create another file
提问by coffeemonitor
I created a simple shell script:
I created a simple shell script:
#!/bin/bash
clear
echo "Starting Script now....."
echo "Write the info below to a new file in same directory...."
echo "name: John Smith"
echo "email: [email protected]
echo "gender: M"
echo
echo
echo "File is done"
I want to create a file in the same directory with the Name, email, and gender details. I don't want to do it from the command line like this:
I want to create a file in the same directory with the Name, email, and gender details. I don't want to do it from the command line like this:
#./script.sh > my.config
I'd rather do it from within the file itself.
I'd rather do it from within the file itself.
回答by Ignacio Vazquez-Abrams
Heredoc.
Heredoc.
cat > somefile << EOF
name: ...
...
EOF
回答by CB Bailey
You can just do:
You can just do:
#!/bin/bash
clear
echo "Starting Script now....."
echo "Write the info below to a new file in same directory...."
# save stdout to fd 3; redirect fd 1 to my.config
exec 3>&1 >my.config
echo "name: John Smith"
echo "email: [email protected]"
echo "gender: M"
echo
echo
# restore original stdout to fd 1
exec >&3-
echo "File is done"
回答by Chargaff
Well, just add >> yourfile to the echo lines you want to write :
Well, just add >> yourfile to the echo lines you want to write :
echo "name: John Smith" >> yourfile
echo "email: [email protected]" >> yourfile
echo "gender: M" >> yourfile
回答by mathematical.coffee
For all your echo "name:John Smith"lines add a > $1(ie first parameter passed in to the script).
For all your echo "name:John Smith"lines add a > $1(ie first parameter passed in to the script).
Then run the script like ./script.sh my.config.
Then run the script like ./script.sh my.config.
Or you could replace the $1with my.configand just run ./script.sh.
Or you could replace the $1with my.configand just run ./script.sh.

