回显行没有正确重定向到 bash 脚本?

echo lines not redirecting into bash script properly?

我必须使用重定向和回显命令从另一个 bash 脚本创建一个 bash 脚本 (mkbackup.sh)。该文件是在正确的位置创建的,但是当我在 vi 上输入它时,只有我输入的最后一行 (fi) 在文件中。我已经更改了授予 rwx 访问权限,你知道发生了什么事吗?

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 \"\"" > "$location"/"$new_file"/backups/mkbackup.sh
echo "    given_file=\"\"" > "$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 [\" \" == \"-z\" ]; then" > "$location"/"$new_file"/backups/mkbackup.sh
echo "        tar -cf \"\" ../src/*.*" > "$location"/"$new_file"/backups/mkbackup.sh
echo "        cp \"\" ../backups/" > "$location"/"$new_file"/backups/mkbackup.sh
echo "    else" > "$location"/"$new_file"/backups/mkbackup.sh
echo "        tar -zcf \"\" ../src/*.*" > "$location"/"$new_file"/backups/mkbackup.sh
echo "        cp \"\" ../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 [\" \" == \"-z\" ]; then" > "$location"/"$new_file"/backups/mkbackup.sh
echo "        tar -cf \"\" ../src/\"\"" > "$location"/"$new_file"/backups/mkbackup.sh
echo "        cp \"\" ../backups/" > "$location"/"$new_file"/backups/mkbackup.sh
echo "    else" > "$location"/"$new_file"/backups/mkbackup.sh
echo "        tar -zcf \"\" ../src/\"\"" > "$location"/"$new_file"/backups/mkbackup.sh
echo "        cp \"\" ../backups/" > "$location"/"$new_file"/backups/mkbackup.sh
echo "    fi" > "$location"/"$new_file"/backups/mkbackup.sh

谢谢!

> 截断目标文件,这样你写的每一行都会覆盖该文件中之前的内容。您可以使用 >>append 到目标文件,但是使用单个 cat 进程写入您打开的文件这整个事情会更清晰 一次,以及大大简化引用。

target=$(pwd)/$new_file/backups/mkbackup.sh

cat <<EOF > "$target"
#!/bin/bash
#MYNAME
#MYID
if [ $# -eq 0 ]; then
    cp -r ../backup/ ../src/*.*
fi
...
EOF