作者 主題: shell script 變數使用問題  (閱讀 1898 次)

0 會員 與 1 訪客 正在閱讀本文。

jjchiou

  • 懷疑的國中生
  • **
  • 文章數: 68
    • 檢視個人資料
shell script 變數使用問題
« 於: 2022-01-07 10:35 »
你好;
我寫了一個shell script,要將文字檔每一行抓入重複輸出文另外script文件.
Shell scripts內容如下:

#!/bin/bash
u=(\/32)
#echo "The numbers in the file are:"
while IFS= read -r line
do
  echo "config firewall address
edit $line
set type ipmask
set subnet $line$u
next"
done < file.txt >ip.txt

file為每行一個ip位址:如 95.216.145.1
我需要輸出為底下格式:

config firewall address
edit 95.216.145.1
set type ipmask
set subnet 95.216.145.1/32
next

但實際輸出格式為:
config firewall address
edit 95.216.145.1
set type ipmask
/32 subnet 95.216.145.1
next
請問要如何改這shell script

darkranger

  • 榮譽學長
  • 俺是博士!
  • *****
  • 文章數: 1382
    • 檢視個人資料
    • https://darkranger.no-ip.org
Re: shell script 變數使用問題
« 回覆 #1 於: 2022-01-10 13:59 »
確定是用 Bash 執行 script 的嗎?
或者,u 那邊換寫法試試看,比如說 u="/32"

jjchiou

  • 懷疑的國中生
  • **
  • 文章數: 68
    • 檢視個人資料
Re: shell script 變數使用問題
« 回覆 #2 於: 2022-01-12 17:27 »
改成 u="/32"一樣是錯誤格式

darkranger

  • 榮譽學長
  • 俺是博士!
  • *****
  • 文章數: 1382
    • 檢視個人資料
    • https://darkranger.no-ip.org
Re: shell script 變數使用問題
« 回覆 #3 於: 2022-01-13 10:10 »
系統環境可能得陳述一下了,畢竟我沒有重現出跟你一樣的問題?

twu2

  • 管理員
  • 俺是博士!
  • *****
  • 文章數: 5416
  • 性別: 男
    • 檢視個人資料
    • http://blog.teatime.com.tw/1
Re: shell script 變數使用問題
« 回覆 #4 於: 2022-01-14 09:27 »
file.txt 為 dos 格式 (CRLF).
請改成 unix 格式 (LF).

讀進來的 $line 最後有 CR, 會跳到那一行的最前面, 所以 /32 會跑到前面蓋掉 set.

jjchiou

  • 懷疑的國中生
  • **
  • 文章數: 68
    • 檢視個人資料
Re: shell script 變數使用問題
« 回覆 #5 於: 2022-01-21 16:02 »
謝謝各位回復,的確是格式的問題,加上一行變換格式就好了