I have to create a bash script (mkbackup.sh) from another bash script using redirection and echo commands. The file is created in the correct location, however when I enter it on vi only the last line I inputted (fi) is in the file. I have changed the permission to grant rwx access, do you have any idea what's going on?
location=$(pwd)
echo "\"$location\"/\"$new_file\""
touch "$location"/"$new_file"/backups/mkbackup.sh
chmod rwx "$location"/"$new_file"/backups/mkbackup.sh
echo "#!/bin/bash" > "$location"/"$new_file"/backups/mkbackup.sh
echo "#MYNAME" > "$location"/"$new_file"/backups/mkbackup.sh
echo "#MYID" > "$location"/"$new_file"/backups/mkbackup.sh
echo "if [ $# -eq 0 ]; then" > "$location"/"$new_file"/backups/mkbackup.sh
echo " cp -r ../backup/ ../src/*.*" > "$location"/"$new_file"/backups/mkbackup.sh
echo "fi" > "$location"/"$new_file"/backups/mkbackup.sh
echo "if [ $# -eq 1 ]; then" > "$location"/"$new_file"/backups/mkbackup.sh
echo " echo \"$1\"" > "$location"/"$new_file"/backups/mkbackup.sh
echo " given_file=\"$1\"" > "$location"/"$new_file"/backups/mkbackup.sh
echo " cp \"$given_file\" ../src/" > "$location"/"$new_file"/backups/mkbackup.sh
echo "fi" > "$location"/"$new_file"/backups/mkbackup.sh
echo "if [ $# -eq 3 ]; then" > "$location"/"$new_file"/backups/mkbackup.sh
echo " if [\" $1\" == \"-z\" ]; then" > "$location"/"$new_file"/backups/mkbackup.sh
echo " tar -cf \"$2\" ../src/*.*" > "$location"/"$new_file"/backups/mkbackup.sh
echo " cp \"$2\" ../backups/" > "$location"/"$new_file"/backups/mkbackup.sh
echo " else" > "$location"/"$new_file"/backups/mkbackup.sh
echo " tar -zcf \"$2\" ../src/*.*" > "$location"/"$new_file"/backups/mkbackup.sh
echo " cp \"$2\" ../backups/" > "$location"/"$new_file"/backups/mkbackup.sh
echo " fi" > "$location"/"$new_file"/backups/mkbackup.sh
echo "fi" > "$location"/"$new_file"/backups/mkbackup.sh
echo "if [ $# -eq 4 ]; then" > "$location"/"$new_file"/backups/mkbackup.sh
echo " if [\" $1\" == \"-z\" ]; then" > "$location"/"$new_file"/backups/mkbackup.sh
echo " tar -cf \"$2\" ../src/\"$4\"" > "$location"/"$new_file"/backups/mkbackup.sh
echo " cp \"$2\" ../backups/" > "$location"/"$new_file"/backups/mkbackup.sh
echo " else" > "$location"/"$new_file"/backups/mkbackup.sh
echo " tar -zcf \"$2\" ../src/\"$4\"" > "$location"/"$new_file"/backups/mkbackup.sh
echo " cp \"$2\" ../backups/" > "$location"/"$new_file"/backups/mkbackup.sh
echo " fi" > "$location"/"$new_file"/backups/mkbackup.sh
Thank you!
CodePudding user response:
>
truncates the target file, so that every line you write is overwriting whatever was previously in that file. You could use >>
to append to the target file, but this whole thing would be cleaner using a single cat
process to write to a file that you open once, as well as simplifying the quoting greatly.
target=$(pwd)/$new_file/backups/mkbackup.sh
cat <<EOF > "$target"
#!/bin/bash
#MYNAME
#MYID
if [ $# -eq 0 ]; then
cp -r ../backup/ ../src/*.*
fi
...
EOF