我需要从脚本中生成脚本,但是有问题,因为新脚本中的一些命令是被解释的,而不是写入到新文件中。例如,我想在其中创建一个名为start.sh的文件,我想将一个变量设置为当前的IP地址:
echo "localip=$(ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1 -d'/')" > /start.sh写入文件的内容是:
localip=192.168.1.78但我想要的是新文件中的以下文本:
localip=$(ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1 -d'/')"以便在运行生成的脚本时确定IP。
我做错什么了?
发布于 2015-08-18 16:05:07
你让这件事变得没必要。使用带有引号的heredoc来传递文字内容,而不需要任何类型的扩展:
cat >/start.sh <<'EOF'
localip=$(ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1 -d'/')
EOF使用<<'EOF'或<<\EOF (而不是只使用<<EOF )是必不可少的;后者将执行扩展,就像您的原始代码一样。
顺便说一句,如果您要写给start.sh的任何东西都需要基于当前变量,那么一定要使用printf %q来安全地转义它们的内容。例如,将当前的$1、$2等设置为在start.sh执行期间处于活动状态:
# open start.sh for output on FD 3
exec 3>/start.sh
# build a shell-escaped version of your argument list
printf -v argv_str '%q ' "$@"
# add to the file we previously opened a command to set the current arguments to that list
printf 'set -- %s\n' "$argv_str" >&3
# pass another variable through safely, just to be sure we demonstrate how:
printf 'foo=%q\n' "$foo" >&3
# ...go ahead and add your other contents...
cat >&3 <<'EOF'
# ...put constant parts of start.sh here, which can use $1, $2, etc.
EOF
# close the file
exec 3>&-这比在每个需要追加的行上使用>>/start.sh要高效得多:使用exec 3>file,然后>&3只打开文件一次,而不是在每个生成输出的命令打开它一次。
https://stackoverflow.com/questions/32077318
复制相似问题