簡體   English   中英

從bash腳本生成bash腳本

[英]Generating a bash script from a bash script

我需要從腳本中生成一個腳本但是遇到問題,因為正在解釋進入新腳本的一些命令而不是寫入新文件。 例如,我想在其中創建一個名為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。

我究竟做錯了什么 ?

你這不必要了。 使用帶有引號的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只打開文件一次,而不是每生成一次輸出的命令打開一次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM