如何创建一个创建文件并在其中写入变量的bash脚本(使用sudo)?

时间:2017-06-28 23:24:14

标签: git bash shell

我想创建一个bash脚本来创建一个git-hook,所以我可以运行$ bash ./create-hook.sh example.com并创建这个文件:

#!/bin/sh
NAME="example.com"
TARGET="/var/www/${NAME}"
TEMP="/var/www/${NAME}_temp"
REPO="/srv/git/${NAME}.git"

mkdir -p $TEMP
git --work-tree=$TEMP --git-dir=$REPO checkout -f
rm -rf $TARGET/*
mv $TEMP/* $TARGET
rm -rf $TEMP
# etc.

```

所以这是脚本的当前状态(不工作):

#!/bin/sh

if [[ $# -eq 0 ]]
  then
    echo 'No name provided'
    exit 1
fi

sudo bash -c 'cat << EOF > post-receive
TARGET="/var/www/$1"
TEMP="/var/www/$1_temp"
REPO="/srv/git/$1.git"

mkdir -p \$TEMP
git --work-tree=\$TEMP --git-dir=\$REPO checkout -f
rm -rf \$TARGET/*
mv $TEMP/* \$TARGET
rm -rf \$TEMP

如何将变量$1从命令行传递到创建的文件?

2 个答案:

答案 0 :(得分:0)

&lt;&lt; EOF * 将写入之后的任何内容,直到您将EOF写入文件,因此$ 1将像这样(文本$1)发送到文件中。我想你必须通过echoing来编写文件:

( echo TARGET='"/var/www'$1'"'; echo TEMP='"/var/www/'$1'_temp"'; echo REPO='"/srv/git/'$1'.git"'; etc etc ) > post_receive

或者那些行

答案 1 :(得分:0)

我使用tee …代替bash -c 'cat…找到了解决方案here

sudo tee > post-receive << EOF
TARGET="/var/www/$1"
# …
EOF
相关问题