簡體   English   中英

shell $字符將覆蓋先前的變量

[英]shell $ character overwrites the previous variable

我正在嘗試在shell上編寫腳本,但遇到了麻煩。

我有一個程序每天創建數據並將其home/meee/data/2013/07/22/mydata這樣的目錄中: home/meee/data/2013/07/22/mydata

我的問題是我想使用日期更改目錄。 這是我的腳本:

#!/bin/sh

x=$(date -u -v-2H "+%Y-%m-%d")
echo $x
year=$(echo $x | cut -d"-" -f1)
month=$(echo $x | cut -d"-" -f2)
day=$(echo $x | cut -d"-" -f3)
echo $year
echo $month
echo $day

d1='/home/sensor/data/'${year}/${month}
echo $d1

year, day, month無關,他們在工作。 但是echo d1的輸出是/07me/sensor/data/2013 同樣,當我編寫echo $year$day它得到2312 (characters of day is overwritten on the first two characater of the year)

我嘗試了許多其他語法,例如代替' character put "或將其保留為空。刪除{等等。但是什么都沒有改變。

不久,當我在同一行中寫入兩個變量($var1 $var2) ,第二個$行為類似於轉到該行的開頭並開始覆蓋第一個變量。

我一直在尋找,但沒有與此相關的東西,或者我找不到任何相關的東西,並且在Stackoverflow中有很多解決方案可以使用$var1$var2解決該問題

我在做什么錯,或者我該如何解決。

我正在使用FreeBSD 9.0-RELEASE amd64並使用sh

任何幫助將不勝感激。

謝謝

不知何故,您的命令正在將回車符引入變量,當變量不是最后echo的變量時,這將影響輸出。 您可以通過將值傳遞給hexdumpod來確認這一點:

printf "%s" "$x" | hexdump -C   # Look for 0d in the output.
printf "%s" "$year" | hexdump -C   # Look for 0d in the output.
printf "%s" "$month" | hexdump -C   # Look for 0d in the output.
printf "%s" "$day" | hexdump -C   # Look for 0d in the output.

我認為這不會解決問題,但是您可以得到年,月和日,而無需花費太多外部程序:

IFS=- read year month day <<EOF
$(date -u -v-2H "+%Y-%m-%d")
EOF

或更簡單

read year month day <<EOF
$(date -u -v-2H "+%Y %m %d")
EOF

您可能在Windows®上使用MinGW或其他非Unix環境,該環境在行尾引入了回車符(CR,\\ r)(來自Unix PoV)。

因此,將其更改為:

x=$(date -u -v-2H "+%Y-%m-%d" | sed $'s/\r$//')
echo $x
year=$(echo $x | cut -d"-" -f1 | sed $'s/\r$//')
month=$(echo $x | cut -d"-" -f2 | sed $'s/\r$//')
day=$(echo $x | cut -d"-" -f3 | sed $'s/\r$//')

或者,甚至更好:

x=$(date -u -v-2H "+%Y %m %d ")
echo $x
set -- $x
year=$1
month=$2
day=$3

請注意%d之后的多余空間,以確保CR變為$ 4,而不是固定在當天。

暫無
暫無

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

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