使用变量创建bash脚本的Bash脚本

时间:2014-02-05 23:19:33

标签: bash variables

我正在编写一个名为“NewProject”的Bash,它创建了第二个名为“compile”的Bash脚本。两个脚本都必须能够将参数作为输入。我的问题是我不能在编译脚本中写入“$ 1” - 这只是将NewProject的第一个参数的内容复制到编译脚本中。这是创建编译脚本的NewProject脚本的一部分。

echo "#!/bin/bash" > $1/compile
echo "
if [[ -z '$1' ]];
then
        echo "You are missing file names. Type in: compile -o executable files."
        exit 1
fi" >> $1/compile
chmod u+x $1/compile

这是NewProject脚本的测试运行输出。

#!/bin/bash

if [[ -z 'testproject4' ]];

then
        echo You are missing file names. Type in: compile -o executable files.
        exit 1
fi

如何更改NewProject脚本以使编译脚本包含'testproject4'而不是'$1'

2 个答案:

答案 0 :(得分:3)

引用时应该更准确。

echo "$1" >>$1/compile

会将NewProject的第一个参数的值附加到编译脚本中。

然而:

echo '$1' >>$1/compile

会将$1个字符附加到编译脚本中。

答案 1 :(得分:0)

我会使用heredoc

cat <<'END' > "$1"/compile
#!/bin/bash

if [[ -z $1 ]];
then
        echo "You are missing file names. Type in: compile -o executable files."
        exit 1
fi
END
chmod u+x "$1"/compile

当你引用heredoc终结词(cat <<'END')时,它会有效地引用整个文档

相关问题