从bash脚本生成bash脚本 [英] Generating a bash script from a bash script

查看:54
本文介绍了从bash脚本生成bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从一个脚本中生成一个脚本,但是遇到了问题,因为进入新脚本的某些命令是被解释而不是写入新文件的.例如,我想在其中创建一个名为start.sh的文件,我想将一个变量设置为当前IP地址:

I need to generate a script from within a script but am having problems because some of the commands going into the new script are being interpreted rather than written to the new file. For example i want to create a file called start.sh in it I want to set a variable to the current IP address:

echo "localip=$(ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/')" > /start.sh

写入文件的内容是:

localip=192.168.1.78

但是我想要的是新文件中的以下文本:

But what i wanted was the following text in the new file:

localip=$(ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/')"

以便在运行生成的脚本时确定IP.

so that the IP is determined when the generated script is run.

我在做什么错了?

推荐答案

您正在使此不必要的工作变得困难.使用带有引号(sigil)的Heredoc可以传递文字内容,而无需进行任何扩展:

You're making this unnecessary hard. Use a heredoc with a quoted sigil to pass literal contents through without any kind of expansion:

cat >/start.sh <<'EOF'
localip=$(ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/')
EOF

使用<<'EOF'<< \ EOF ,而不是<< EOF ,是必不可少的;后者将像您的原始代码一样执行扩展.

Using <<'EOF' or <<\EOF, as opposed to just <<EOF, is essential; the latter will perform expansion just as your original code does.

顺便说一句,如果要写入 start.sh 的任何内容都需要基于当前变量,请确保使用 printf%q 安全地逃避它们内容.例如,要将您当前的 $ 1 $ 2 等设置为在 start.sh 执行期间处于活动状态:

If anything you're writing to start.sh needs to be based on current variables, by the way, be sure to use printf %q to safely escape their contents. For instance, to set your current $1, $2, etc. to be active during start.sh execution:

# 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 只打开一次文件,而不是每个生成输出的命令一次打开文件.

This is far more efficient than using >>/start.sh on every line that needs to append: Using exec 3>file and then >&3 only opens the file once, rather than opening it once per command that generates output.

这篇关于从bash脚本生成bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆