简体   繁体   English

Bash脚本CAT命令使用脚本参数,而不是在cat'd文件中保留$ 1

[英]Bash script CAT command uses the script parameters rather than leaving $1 in the cat'd file

I am having a bit of an issue with a bash script when trying to cat a new file. 尝试建立新文件时,bash脚本存在一些问题。

#!/bin/bash


#sudo vim /etc/init.d/glassfish

sudo cat > /etc/init.d/glassfish <<EOF

# Set path variable
GLASSFISH_HOME=/opt/glassfish3

# Establish Commands
case "$1" in
start)
    ${GLASSFISH_HOME}/bin/asadmin start-domain domain1
    ;;
stop)
    ${GLASSFISH_HOME}/bin/asadmin stop-domain domain1
    ;;
restart)
    ${GLASSFISH_HOME}/bin/asadmin stop-domain domain1
    ${GLASSFISH_HOME}/bin/asadmin start-domain domain1
    ;;
*)
    echo "usage: $0 {start|stop|restart}"
    ;;
esac    
exit 0
EOF>

However, when I run this script it replaces the $1 and $0 with what I used to call the script that runs the command, so $1 becomes "" and $0 becomes testscript.sh 但是,当我运行此脚本时,它将$ 1和$ 0替换为我用来运行命令的脚本,因此$ 1变为“”,而$ 0变为testscript.sh

Is there any way to prevent this? 有什么办法可以防止这种情况?

If the here document delimiter is entirely unquoted, the contents are treated as a double-quoted string. 如果此处文档定界符完全未加引号,则将内容视为双引号字符串。 Quote at least one character of the delimiter (it's simplest to just quote the whole thing) to have the here document treated as a single-quoted string, preventing parameter expansion. 引号中至少要包含一个定界符(最简单的做法是将整个引号引起来),以将here文档视为单引号字符串,以防止参数扩展。

sudo tee /etc/init.d/glassfish > /dev/null <<'EOF'
...
EOF

Why did I use tee instead of cat ? 为什么我用tee代替cat The output redirection is not affected by sudo , since the file is opened by the shell before sudo even runs. 输出重定向不受sudo影响,因为该文件 sudo甚至运行之前 sudo由外壳程序打开。 If you need sudo because you don't otherwise have write permission to /etc/init.d/ , you need to run a command like tee that opens the file itself. 如果由于没有对/etc/init.d/写许可权而需要sudo ,则需要运行类似tee的命令来打开文件本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM