2016-10-10 36 views
0

我有一堆目錄的過程,所以我開始一個循環是這樣的:

foreach n (1 2 3 4 5 6 7 8) 

然後我有一大堆的命令在那裏我複製了來自不同地方

cp file1 dir$n 
cp file2 dir$n 

一些文件,但我有一對夫婦的命令,其中$ n是在命令中像這樣的中間:

cp -r dir$nstep1 dir$n 

當我運行這個命令時,shell會抱怨找不到變量$ nstep1。我想要做的是先評估$ n,然後連接它周圍的文本。我嘗試使用`和(),但都沒有工作。如何在csh中做到這一點?

+0

'dir $ {n} step1' - 用大括號包圍名稱。 –

+0

另外:csh中的腳本通常不被認爲是一個好主意。參見[不使用C Shell的十大理由](http://www.grymoire.com/Unix/CshTop10.txt)或[作者最近更新的關於同一主題的頁面](http:// www .grymoire.com/UNIX/Csh.html);或經典的[CSH編程被認爲是有害的](http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/)。 –

+0

我c。我注意到csh中的一些語法有點奇怪,有些事情花了很長時間才能調試。當我登錄到這個系統時,我只是懶於更改我的默認shell,但是聽起來好像將shell改爲bash在長期內是值得的。 –

回答

2

在這方面的行爲類似於POSIX殼:

cp -r "dir${n}step1" "dir${n}" 

引號防止串分裂和水珠擴張。觀察這意味着什麼,比較如下:

# prints "hello * cruel * world" on one line 
set n=" * cruel * " 
printf '%s\n' "hello${n}world" 

...這樣的:

# prints "hello" on one line 
# ...then a list of files in the current directory each on their own lines 
# ...then "cruel" on another line 
# ...then a list of files again 
# ... and then "world" 
set n=" * cruel * " 
printf '%s\n' hello${n}world 

在現實世界的情況下,正確的引用這樣可以刪除奇怪名稱的文件之間的差異你正在嘗試操作,並刪除目錄中的所有其他內容。

+0

是否需要引號? –

+0

@TonyRuth,......修正以明確這一點。 –